Broadcasting
How NumPy handles operations between arrays of different shapes
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Broadcasting lets NumPy operate on arrays with different shapes by "stretching" the smaller array to match the larger one — without copying data.
Simple case — scalar:
python a = np.array([1, 2, 3]) a + 10 # [11, 12, 13] — 10 is broadcast to match shape (3,)
2D case:
python m = np.ones((3, 4)) # shape (3, 4) v = np.array([1, 2, 3, 4]) # shape (4,) m + v # v is broadcast across all 3 rows # [[2, 3, 4, 5], # [2, 3, 4, 5], # [2, 3, 4, 5]]
Broadcasting rules:
- 1. If arrays have different numbers of dimensions, pad the smaller shape with 1s on the left
- 2. Dimensions of size 1 are stretched to match the other array
- 3. If sizes don't match and neither is 1 → error
Common use case — normalization:
python data = np.random.rand(100, 5) # 100 samples, 5 features data = (data - data.mean(axis=0)) / data.std(axis=0)
Examples
Subtract column means from each row
col_means shape (3,) broadcasts across the (3,3) matrix
import numpy as np
data = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
col_means = data.mean(axis=0) # [40, 50, 60]
centered = data - col_means # broadcast across rows
print(centered)
# [[-30, -30, -30],
# [ 0, 0, 0],
# [ 30, 30, 30]]How well did you understand this?
Next in NumPy
Boolean Masking