Sub topic 9
Broadcasting rules
This chapter assumes you can create arrays, read shape, and apply elementwise operations such as a + b on arrays of the same shape. Here you learn what NumPy does when the shapes differ.
What broadcasting does
Broadcasting is the set of rules NumPy uses to combine arrays of different shapes in one elementwise operation. NumPy does not copy the smaller array into a bigger one. It reuses the same values along the axes that need stretching, so the operation stays fast and uses little extra memory.
The two rules
NumPy compares the two shapes starting from the last (rightmost) axis and works toward the first.
- If one shape has fewer axes, NumPy treats it as if it had extra axes of size 1 on its left.
- Two sizes on the same axis are compatible if they are equal or if one of them is 1. An axis of size 1 is stretched to match the other size.
If any axis pair fails both tests, NumPy raises a ValueError. The result shape takes the larger size on each axis.
Worked examples
| Shape A | Shape B | Padded comparison | Result |
|---|---|---|---|
| (3, 4) | (4,) | (3, 4) vs (1, 4) | (3, 4) |
| (3, 1) | (1, 4) | 3 vs 1, 1 vs 4 | (3, 4) |
| (3, 1) | (4,) | (3, 1) vs (1, 4) | (3, 4) |
| (5, 1, 4) | (3, 1) | (5, 1, 4) vs (1, 3, 1) | (5, 3, 4) |
| (2, 3) | (3, 2) | 3 vs 2 fails | error |
The third row is the standard way to build a grid. A column of shape (3, 1) and a row of shape (4,) each stretch along the axis where they have size 1:
import numpy as np
col = np.arange(3).reshape(3, 1) # shape (3, 1)
row = np.arange(4) # shape (4,)
grid = col + row # shape (3, 4)
print(grid)
# [[0 1 2 3]
# [1 2 3 4]
# [2 3 4 5]]Each cell grid[i, j] equals col[i, 0] + row[j].
Checking shapes without running the operation
np.broadcast_shapes applies the rules to shapes alone. Use it to test your prediction before you work with large arrays.
import numpy as np
print(np.broadcast_shapes((3, 1), (4,))) # (3, 4)
print(np.broadcast_shapes((5, 1, 4), (3, 1))) # (5, 3, 4)
try:
np.broadcast_shapes((2, 3), (3, 2))
except ValueError as err:
print("error:", err)Common mistakes
- Reading shapes from the left. The comparison always starts at the right, so
(3, 4)and(3,)fail, because 4 is compared with 3. - Assuming a 1D array is a column. A shape
(n,)array behaves like a row, so it lines up with the last axis. - Forgetting that size 1 is special. A shape
(3, 1)array stretches to any width, but a shape(3,)array stretches only if the other side's last axis is 1 or 3.
You will fix mismatches in a later chapter with np.newaxis and keepdims.
Exercise
Do shapes (8, 1, 6) and (7, 1) broadcast? If they do, what is the result shape?
Show answer
Yes. Pad (7, 1) to (1, 7, 1). Compare from the right: 6 vs 1 gives 6, 1 vs 7 gives 7, and 8 vs 1 gives 8. The result shape is (8, 7, 6).
Exercise
Why does adding an array of shape (3, 4) to an array of shape (3,) fail, and which shape for the second array would make it work as a column?
Show answer
The last axes are compared first, and 4 and 3 are neither equal nor 1. Shape (3, 1) works, because its last axis is 1 and stretches to 4. Reshape the vector with v[:, np.newaxis].