So far we have built arrays and selected from them. Now we calculate with them. This fourth part of our NumPy Fundamentals series covers vectorised maths, doing arithmetic on whole arrays with no loops, and broadcasting, the set of rules that lets NumPy combine arrays of different shapes. Broadcasting is the idea that confuses most beginners, so we take it slowly, with a real example: turning a table of exam marks into weighted totals.
Arithmetic on whole arrays
When two arrays have the same shape, arithmetic operators work element by element:
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
print(a + b)
print(a * b)
print(b / a)
print(a ** 2)
[11 22 33 44]
[ 10 40 90 160]
[10. 10. 10. 10.]
[ 1 4 9 16]
Each result is a new array of the same shape. There is no loop to write and no index to get wrong. In the Python Fundamentals series we wrote functions that looped over a list to do this; here the operator itself does the work, in compiled code. Note that / always gives floats, even when the answers are whole numbers.
Universal functions
NumPy's mathematical functions, called ufuncs (universal functions), also work on every element:
print(np.sqrt(np.array([4, 9, 16])))
print(np.round(np.array([1.234, 5.678]), 1))
[2. 3. 4.]
[1.2 5.7]
There are ufuncs for almost everything: np.abs, np.exp, np.log, np.sin, np.maximum and many more. Use them instead of Python's math module, whose functions only accept a single number.
Scalars broadcast automatically
You have already used the simplest kind of broadcasting. When you combine an array with a single number, the number is applied to every element. Converting temperatures from Celsius to Fahrenheit is one line:
celsius = np.array([18.5, 25.0, 31.2, 40.0])
print(celsius * 9 / 5 + 32)
[ 65.3 77. 88.16 104. ]
NumPy treats the single numbers 9, 5 and 32 as if they were arrays of the same shape as celsius, without actually creating those arrays in memory. That is broadcasting.
Broadcasting a row across a table
Broadcasting goes further than single numbers. Here are three students' marks in three tests, and the weight of each test in the final result:
marks = np.array([[60, 75, 80],
[45, 90, 70],
[88, 66, 92]])
weights = np.array([0.2, 0.3, 0.5])
print(marks * weights)
print((marks * weights).sum(axis=1))
[[12. 22.5 40. ]
[ 9. 27. 35. ]
[17.6 19.8 46. ]]
[74.5 71. 83.4]
marks has shape (3, 3) and weights has shape (3,). NumPy stretches the single row of weights down across all three rows, so each column is multiplied by its own weight. Summing along axis=1 (across each row) gives each student's weighted total: 74.5, 71 and 83.4. Doing this with nested loops would take several lines and be much slower; we explain axis fully in Part 6.
The broadcasting rules
NumPy compares the two shapes from the right-hand end, one dimension at a time. Two dimensions are compatible when:
- they are equal, or
- one of them is 1 (or missing).
A dimension of size 1 is stretched to match the other. That is why a column and a row combine into a full table:
col = np.array([[1], [2], [3]]) # shape (3, 1)
row = np.array([10, 20, 30]) # shape (3,)
print(col + row)
[[11 21 31]
[12 22 32]
[13 23 33]]
The column is stretched across, the row is stretched down, and the result has shape (3, 3). This pattern, "every combination of these two lists", comes up constantly, for example in distance tables or price-by-quantity grids.
When neither rule applies, NumPy refuses rather than guessing:
try:
np.array([1, 2, 3]) + np.array([1, 2])
except ValueError as e:
print("ValueError:", e)
ValueError: operands could not be broadcast together with shapes (3,) (2,)
The error message tells you both shapes, which is usually all you need to spot the problem. Checking .shape of each array is the first debugging step for any broadcasting error, and Part 5 shows how to reshape an array so the shapes line up.

Why vectorise?
Vectorised code is faster, as we measured in Part 1, but speed is not the only win. It is also shorter and closer to the maths you would write on paper: celsius * 9 / 5 + 32 is the formula itself. Fewer loops means fewer off-by-one mistakes. When you catch yourself writing for i in range(len(arr)) over an array, stop and look for the vectorised version.
A real use: scaling features to 0–1
Broadcasting is behind one of the most common steps in machine learning: scaling. Models often behave badly when one column is measured in hundreds (height in cm) and another in tens (weight in kg), so each column is rescaled to run from 0 to 1. The formula is (value − column minimum) / (column maximum − column minimum), and with broadcasting it works on the whole table at once:
X = np.array([[150, 50],
[160, 65],
[170, 80],
[180, 95]], dtype=float)
mins, maxs = X.min(axis=0), X.max(axis=0)
print(((X - mins) / (maxs - mins)).round(2))
[[0. 0. ]
[0.33 0.33]
[0.67 0.67]
[1. 1. ]]
X has shape (4, 2), while mins and maxs each have shape (2,): one value per column. Using the rules above, NumPy compares from the right, sees 2 and 2, and stretches each row of minimums down all four rows. Every column is scaled by its own minimum and maximum without a single loop. This is exactly what scikit-learn's MinMaxScaler does internally.
The same pattern gives you standardisation (subtract the column mean, divide by the column standard deviation), which we use to spot outstanding students in the project. Whenever you need "do this to each column using that column's statistic", the answer is a per-column summary with axis=0 and then broadcasting.
Practice exercises
- Three products cost 250, 499 and 1200. Build a price table for quantities 1, 2 and 3 using broadcasting, with one row per quantity.
- Find the length of the vector (3, 4), the square root of the sum of the squares, without a loop.
- Convert the race distances 5, 12.5 and 21.1 km to miles (1 km = 0.621371 miles), rounded to 2 decimals.
prices = np.array([250, 499, 1200])
qty = np.array([[1], [2], [3]])
print(prices * qty)
x = np.array([3.0, 4.0])
print(np.sqrt((x ** 2).sum()))
km = np.array([5, 12.5, 21.1])
print((km * 0.621371).round(2))
[[ 250 499 1200]
[ 500 998 2400]
[ 750 1497 3600]]
5.0
[ 3.11 7.77 13.11]
In the first answer qty is a column of shape (3, 1) and prices a row of shape (3,), so broadcasting builds every quantity-times-price combination, exactly like the column-plus-row example above.
Common mistakes
- Expecting
*to be matrix multiplication. For arrays,*multiplies element by element. Matrix multiplication is@, covered in Part 7. - Integer division surprises.
/always returns floats; use//if you want floor division on integers. - Shape mismatches. Print both
.shapevalues and compare them from the right using the two rules above. - Using
math.sqrton an array. It only takes one number; usenp.sqrt.
Wrapping up
You can now do arithmetic on whole arrays, apply ufuncs, and predict when broadcasting will stretch an array and when it will fail. Next, in Reshaping and Combining Arrays, we learn to change an array's shape, understand axes properly, and join and split arrays.
Comments (0)
No comments yet — be the first to share your thoughts.