Skip to main content
Albero Academy

Broadcasting

Combine arrays of different shapes by virtually stretching the smaller one.

Operations11 min

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

a scalar broadcasts to every element
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):

stretching a row across rows
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 combination
np.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

  1. 01Broadcasting combines different-shaped arrays without copying, by stretching size-1 dimensions.
  2. 02Rule: compare shapes from the right; dims are compatible if equal or one is 1.
  3. 03A scalar broadcasts to every element; a (n,) row broadcasts down every row.
  4. 04It powers column-wise normalisation and pairwise operations in one line.
  5. 05Insert a length-1 axis with [:, None] to make shapes align.

Finished this chapter?

Mark it complete to track your progress through NumPy.