iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Broadcasting

Broadcasting is NumPy’s rule for combining arrays of different shapes. Smaller arrays get “stretched” along axes of size 1 (or missing axes) without copying memory.

The rules + practical patterns

EXAMPLE
import numpy as np

# RULES (right-to-left):
#   1. If shapes differ in length, prepend 1s to the smaller shape.
#   2. Two dimensions are compatible if equal, or one of them is 1.
#   3. The result shape is the per-axis maximum.

# Scalar across an array
a = np.array([1, 2, 3, 4])
print(a + 10)                    # [11, 12, 13, 14]

# Row across a matrix — (3,4) + (4,) → (3,4)
m   = np.arange(12).reshape(3, 4)
row = np.array([10, 20, 30, 40])
print(m + row)

# Column across a matrix — (3,4) + (3,1) → (3,4)
col = np.array([100, 200, 300]).reshape(3, 1)
print(m + col)

# Outer addition — (4,) + (3,) → ??? FAILS
# Need to reshape:
a = np.arange(4)                 # (4,)
b = np.arange(3).reshape(3, 1)   # (3, 1)
print(a + b)                     # (3, 4)

# Normalise rows of a matrix (subtract row mean)
means = m.mean(axis=1, keepdims=True)   # (3, 1) — keepdims keeps broadcast shape
centred = m - means

# Pairwise distances — broadcasting + sqrt
points = np.random.rand(5, 2)
diff   = points[:, None, :] - points[None, :, :]   # (5, 5, 2)
dist   = np.sqrt((diff ** 2).sum(axis=-1))         # (5, 5)

Why it matters

Broadcasting turns explicit loops into one-liners that run at C speed. Almost any time you reach for a for-loop in numerical NumPy code, broadcasting + a reshape will do it faster.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])  # shape (2, 3)
row = np.array([10, 20, 30])         # shape (3,)
print(a + row)                       # (2,3) + (3,) → (2,3)
Try it Yourself »

Test yourself

Q1. Broadcasting lets you operate on…
Q2. (2,3) + (3,) broadcasts to shape…
Q3. (2,3) + (2,) broadcasts…

Discussion

Loading…