Sub topic 9
Broadcasting rules
Broadcasting lets NumPy combine arrays of different shapes in one operation without copying data or writing loops. This chapter assumes you know array shapes, vectorized arithmetic, and axis reductions from the earlier chapters. It covers the rules, how to apply them by hand, how to shape arrays on purpose, and the errors and silent bugs that come up most often.
Why broadcasting exists
Vectorized arithmetic on two arrays of the same shape works elementwise. Real code often needs to combine a matrix with a row of weights, or subtract a per-column mean from every row. You could tile the smaller array to match, but that wastes memory. Broadcasting instead treats the smaller array as if it were repeated along the missing or length-1 dimensions, and it does this without allocating the repeated data.
import numpy as np
rows = np.array([[0], [10], [20]]) # shape (3, 1)
cols = np.array([1, 2, 3]) # shape (3,)
print(rows + cols)
# [[ 1 2 3]
# [11 12 13]
# [21 22 23]]The result has shape (3, 3). The column rows was stretched across columns, and the 1-D cols was stretched down rows.
The two rules
NumPy compares the shapes of two arrays from the last dimension backward, one pair of dimensions at a time.
- Pad. If one shape has fewer dimensions, prepend 1s to it until both have the same number of dimensions.
- Match or stretch. For each pair of dimensions, they are compatible if they are equal or if one of them is 1. The result dimension is the larger of the two. If any pair is incompatible, NumPy raises
ValueError.
Both rules compare shapes only. The values in the arrays never matter. Applying the rules to the opening example:
| Step | `rows` | `cols` |
|---|---|---|
| Original shapes | `(3, 1)` | `(3,)` |
| After padding | `(3, 1)` | `(1, 3)` |
| Last dimension | 1 vs 3, result 3 | |
| First dimension | 3 vs 1, result 3 | |
| Result | `(3, 3)` |
More pairs to practice on:
| Shape A | Shape B | Result |
|---|---|---|
| `(5, 3)` | `(3,)` | `(5, 3)` |
| `(5, 3)` | `(5,)` | error: 3 vs 5 |
| `(5, 1)` | `(1, 4)` | `(5, 4)` |
| `(2, 1, 3)` | `(4, 1)` | `(2, 4, 3)` |
| `(1,)` | `(0,)` | `(0,)` |
| `(3,)` | `(0,)` | error: 3 vs 0 |
The last two rows show the edge case with empty arrays. A dimension of size 1 stretches to 0 just as it stretches to any other size, but 3 and 0 are not compatible.
You can check a combination without building any arrays. np.broadcast_shapes (NumPy 1.20 and later) accepts any number of shapes.
import numpy as np
print(np.broadcast_shapes((3, 1), (1, 4), (4,))) # (3, 4)
try:
np.ones(3) + np.ones(4)
except ValueError as e:
print("ValueError:", e)
# operands could not be broadcast together with shapes (3,) (4,)Centering data: the most common use
Subtracting a column mean is a one-line broadcast. m.mean(axis=0) has shape (3,). Padding turns it into (1, 3), which lines up with the columns of m.
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]]) # shape (2, 3)
print(m - m.mean(axis=0))
# [[-1.5 -1.5 -1.5]
# [ 1.5 1.5 1.5]]Subtracting a row mean needs more care. m.mean(axis=1) has shape (2,). Padding gives (1, 2), and the last dimensions are 3 vs 2, so the operation fails. Use keepdims=True so the mean has shape (2, 1).
import numpy as np
m = np.array([[1, 2, 3], [4, 5, 6]])
print(m - m.mean(axis=1, keepdims=True))
# [[-1. 0. 1.]
# [-1. 0. 1.]]Adding dimensions on purpose
Padding only adds dimensions on the left. To line a 1-D array up with a different axis, insert a length-1 axis yourself with np.newaxis (an alias for None) or with reshape.
import numpy as np
v = np.array([1, 2, 3])
print(v.shape) # (3,)
print(v[:, np.newaxis].shape) # (3, 1), a column
print(v[np.newaxis, :].shape) # (1, 3), a row
print(v.reshape(-1, 1).shape) # (3, 1), same resultInserting axes lets you compute all pairwise combinations. This example finds the distance between every pair of points. pts[:, None, :] has shape (3, 1, 2) and pts[None, :, :] has shape (1, 3, 2). Their difference has shape (3, 3, 2), and summing over the last axis leaves (3, 3).
import numpy as np
pts = np.array([[0, 0], [3, 4], [6, 8]]) # shape (3, 2)
diff = pts[:, None, :] - pts[None, :, :] # shape (3, 3, 2)
dist = np.sqrt((diff ** 2).sum(axis=-1)) # shape (3, 3)
print(dist)
# [[ 0. 5. 10.]
# [ 5. 0. 5.]
# [10. 5. 0.]]What broadcasting does in memory
Broadcasting does not copy the smaller array. Internally, NumPy gives the stretched dimension a stride of 0, so every step along that axis reads the same bytes. np.broadcast_to exposes this directly.
import numpy as np
b = np.broadcast_to(np.arange(3), (4, 3))
print(b.shape) # (4, 3)
print(b.strides) # (0, 8) with int64 elements
print(b.flags.writeable) # FalseThe result is a read-only view. Writing to it would change one source element through many apparent positions, so NumPy forbids it. If you need a writable tiled array, call .copy() on the result.
The inputs are not copied, but the output of an operation like a + b is a new full-size array. This is the main memory risk. Two arrays of shape (100000, 1) and (1, 100000) are tiny, but their sum has 10 billion elements, which is 80 GB at 8 bytes each.
Common errors and silent bugs
Incompatible trailing dimensions. An error like shapes (5,3) (5,) means the last dimensions disagree. Check which axis you meant to align, then reshape one array to (5, 1).
The accidental outer product. This one raises no error. A 1-D array and a column vector broadcast to a 2-D result, which is often not what you wanted.
import numpy as np
v = np.array([1, 2, 3]) # shape (3,)
w = v.reshape(3, 1) # shape (3, 1)
print((v - w).shape) # (3, 3), not (3,)This often appears after a reshape(-1, 1) or after a function returns a column where you expected a flat array. When a result has one more dimension than expected, print the input shapes first.
In-place operations cannot grow the target. For a += b, the broadcast result must have the same shape as a. Otherwise NumPy raises an error instead of reallocating.
import numpy as np
x = np.zeros(3)
try:
x += np.ones((3, 1)) # broadcast shape would be (3, 3)
except ValueError as e:
print("ValueError:", e)
# non-broadcastable output operand with shape (3,) doesn't match
# the broadcast shape (3, 3)Broadcasting also applies to assignment. The right-hand side of an assignment is broadcast to the shape of the selected region, so a[:, 1] = 0 and a[:, 1] = [7, 8] both work when a has two rows.
Checklist for predicting a result
- Write both shapes, right-aligned, one above the other.
- Fill empty leading slots on the shorter one with 1.
- Check each column. Equal sizes, or a 1 on either side, is fine. Anything else is an error.
- The result shape is the column-wise maximum.
- Estimate the output size. If it is far larger than the inputs, consider processing in chunks.
Exercise
You have data with shape (100, 4) and want to scale each row to sum to 1. A colleague writes data / data.sum(axis=1). What happens, and how do you fix it?
Show answer
data.sum(axis=1) has shape (100,). Padding makes it (1, 100), so the last dimensions are 4 vs 100. They are incompatible, so NumPy raises a ValueError. (If the array had shape (100, 100), the code would run without error and divide each column by the wrong sums, which is a silent bug.) The fix is data / data.sum(axis=1, keepdims=True). The sums then have shape (100, 1), which stretches across the 4 columns.
Exercise
What is the result shape of np.ones((2, 1, 3)) + np.ones((5, 1)), and what are the shapes after padding?
Show answer
The second shape is padded to (1, 5, 1). Comparing against (2, 1, 3) from the right gives 3 vs 1 → 3, 1 vs 5 → 5, and 2 vs 1 → 2. The result shape is (2, 5, 3).