Chapter 3 introduced broadcasting; mastering it is what separates elegant NumPy from loop-ridden NumPy. The key skill is reshaping arrays so their dimensions line up — then whole classes of pairwise computation collapse into a single expression.
The rule, precisely
NumPy aligns shapes from the right. Two dimensions are compatible when they are equal, or one of them is 1 (which gets stretched):
# (3, 1) with (1, 4) → compatible → result (3, 4)# 3 1 stretch both 1s# 1 4a = np.array([[1], [2], [3]]) # (3, 1)b = np.array([[10, 20, 30, 40]])# (1, 4)a + b # (3, 4) — every combination
newaxis & adding dimensions
np.newaxis (or None) inserts a length-1 axis so two arrays can broadcast against each other. This is the single most useful broadcasting trick:
v = np.array([1, 2, 3])v[:, np.newaxis] # shape (3, 1) — a columnv[np.newaxis, :] # shape (1, 3) — a row# Column × row → every pairwise product (an outer product)v[:, None] * v[None, :]# [[1 2 3]# [2 4 6]# [3 6 9]]
Outer & pairwise operations
The column-vs-row pattern computes every pair at once. It's how you build a pairwise distance matrix with no loop:
pts = np.array([0.0, 1.0, 4.0])# |pts[i] - pts[j]| for all i, jdist = np.abs(pts[:, None] - pts[None, :])# [[0 1 4]# [1 0 3]# [4 3 0]]np.add.outer([1, 2, 3], [10, 20]) # outer sum via a ufunc
meshgrid
np.meshgrid builds coordinate grids from axis vectors — the standard way to evaluate a function over a 2-D grid (for surfaces and contour plots):
x = np.linspace(-2, 2, 5)y = np.linspace(-2, 2, 5)X, Y = np.meshgrid(x, y)Z = X**2 + Y**2 # the function value at every (x, y) point
Practice
Build a multiplication table for 1–10 in one line using newaxis. Compute the pairwise absolute-difference matrix for a vector of points. Use meshgrid to evaluate z = x² + y² over a grid and find its minimum.
Key takeaways
- 01Broadcasting aligns shapes from the right; dims match when equal or one is 1 (which stretches).
- 02np.newaxis / None inserts a length-1 axis so arrays broadcast — the key reshaping trick.
- 03Column × row (v[:,None] op v[None,:]) computes every pair at once — outer products and distance matrices.
- 04ufunc.outer and np.meshgrid build pairwise results and coordinate grids without loops.
- 05Mastering broadcasting replaces whole nested loops with single vectorised expressions.
