Last updated
Broadcasting
Definition: Broadcasting is how NumPy combines arrays of different shapes. It automatically "stretches" the smaller array across the larger one so the operation works without writing loops.
Example 1 — array and a single number
import numpy as np a = np.array([1, 2, 3]) print(a + 10) # 10 is broadcast to [10 10 10] -> [11 12 13]
Example 2 — 2D and 1D
A 1D row can be added to every row of a 2D array:
import numpy as np
m = np.array([[1, 2, 3],
[4, 5, 6]])
row = np.array([10, 20, 30])
print(m + row) # row is added to each row of m
A practical use — normalising data
import numpy as np data = np.array([10, 20, 30, 40]) print(data - data.mean()) # centre the data around 0
Here data.mean() (a single number) is broadcast across the whole array.
💡 Tip: broadcasting is what lets you scale, shift, and normalise entire datasets in one clean line.
Try it Yourself
Output
Ad · responsive