Array Arithmetic and Broadcasting
In NumPy, you can do math directly on arrays without using loops.
This is called element-wise operations — and it’s fast and clean.
Array Arithmetic
If two arrays are the same size, NumPy will apply operations element by element.
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b) # [11 22 33]
print(a * b) # [10 40 90]
You can also subtract, divide, or raise to powers: a - b
, a / b
, a ** 2
Broadcasting
If arrays are not the same shape, NumPy tries to match them using broadcasting.
This means smaller arrays are “stretched” so the operation can still work.
Broadcasting Example
a = np.array([1, 2, 3])
b = 10
print(a + b) # [11 12 13]
NumPy applied + 10
to every element in a
.
It can also work between 2D and 1D arrays in some cases (you’ll see this in practice).
Summary
- Use
+
,-
,*
,/
,**
directly on arrays - Operations happen element-by-element
- Broadcasting allows arrays of different shapes to work together
What’s Next
You’ll now practice array arithmetic and see how broadcasting works in action.