Lesson 9 of 60 · python
Broadcasting in NumPy
Duration: 20 minutes
Broadcasting
Broadcasting allows NumPy to perform arithmetic operations on arrays of different shapes by implicitly expanding the smaller array.
Simple broadcast example
import numpy as np
A = np.arange(6).reshape(2,3)
B = np.array([10, 20, 30]) # shape (3,)
C = A + B # B is broadcast across rows
print(C)
Rules of broadcasting
- Align dimensions from the right.
- If dimensions are equal, they are compatible.
- If one dimension is 1, the array behaves as if it were copied.
- Otherwise, broadcasting fails.
Higher‑dimensional broadcast
A = np.ones((2,1,3))
B = np.arange(3) # shape (3,)
C = A * B # result shape (2,1,3)
print(C.shape)
When broadcasting fails
np.arange(4) + np.arange(3) # ValueError
Practical tip
Use np.broadcast_to to explicitly broadcast an array:
B = np.arange(3)
B_broadcast = np.broadcast_to(B, (2,3))
print(B_broadcast)