Look at this:
import numpy as np
x = np.array([
[10, 20, 30],
[40, 50, 60]
])
x + 5
You get:
[[15, 25, 35],
[45, 55, 65]]
But where did the
5 go? You didn't write a loop. You didn't copy 5 six times.This is broadcasting.
NumPy automatically treats the smaller object as if it were expanded to match the larger array's shape.
So conceptually:
[[10, 20, 30], [[5, 5, 5],
[40, 50, 60]] + [5, 5, 5]]
Then it adds them element by element.
And it works with arrays too:
x + np.array([1, 2, 3])
Conceptually:
[[10, 20, 30], [[1, 2, 3],
[40, 50, 60]] + [1, 2, 3]]
Result:
[[11, 22, 33],
[41, 52, 63]]
The important part:
Broadcasting doesn't literally copy the data into a bigger array.
NumPy applies the operation as if the smaller array had been expanded, while avoiding unnecessary copies.
That's why this:
x + 5
can work even though
x is 2D and 5 is just a scalar.