Python / Data Science Essentials Interview Questions
What is NumPy broadcasting and how does it work?
Broadcasting is the set of rules NumPy uses to perform element-wise operations on arrays of different but compatible shapes, without physically copying data to make them the same size. It is one of the most powerful and often misunderstood NumPy features.
The rules, applied dimension by dimension starting from the trailing (rightmost) axis:
- If the arrays have different numbers of dimensions, prepend 1s to the shape of the smaller-dimensional array.
- Dimensions of size 1 are stretched to match the other array's size in that dimension.
- If any dimension neither matches nor is 1, a
ValueErroris raised.
import numpy as np # Scalar broadcast over array a = np.array([1, 2, 3]) print(a * 10) # [10 20 30] # (3,) and (3, 1) â column vector subtraction from each column matrix = np.array([[10, 20, 30], [40, 50, 60]]) row_min = matrix.min(axis=1, keepdims=True) # shape (2, 1) normalised = matrix - row_min # broadcasts: (2,3) - (2,1) -> (2,3) print(normalised) # [[ 0 10 20] # [ 0 10 20]] # Outer product via broadcasting col = np.array([[1], [2], [3]]) # shape (3, 1) row = np.array([10, 20, 30]) # shape (3,) -> treated as (1, 3) print(col * row) # [[10 20 30] # [20 40 60] # [30 60 90]]
Broadcasting avoids the memory cost of explicit np.tile or np.repeat calls. The stretched values are never physically written — NumPy just iterates as if they were. For large arrays this can mean the difference between fitting in RAM and running out of memory.
More Related questions...