Broadcasting is the rule that lets NumPy combine arrays of different shapes without copying data. It's how you add a scalar to every element, or subtract a row of column-means from a whole matrix — in one clean line.
The simplest case
m = np.array([[1, 2, 3],[4, 5, 6]]) # shape (2, 3)m + 10 # 10 added to every element
The broadcasting rule
Compare shapes from the right. Two dimensions are compatible when they're equal, or one of them is 1 (which gets stretched):
col_means = m.mean(axis=0) # shape (3,) → [2.5 3.5 4.5]m - col_means # subtract each column's mean (broadcast down)# (3,1) with (1,4) → (3,4): every combinationnp.arange(3)[:, None] * np.arange(4)[None, :]
When it fails
If dimensions are neither equal nor 1, NumPy raises a clear ValueError: operands could not be broadcast together. The fix is almost always inserting a length-1 axis with [:, None] so the shapes line up.
Key takeaways
- 01Broadcasting combines different-shaped arrays without copying, by stretching size-1 dimensions.
- 02Rule: compare shapes from the right; dims are compatible if equal or one is 1.
- 03A scalar broadcasts to every element; a (n,) row broadcasts down every row.
- 04It powers column-wise normalisation and pairwise operations in one line.
- 05Insert a length-1 axis with [:, None] to make shapes align.
