A loop against one expression
Both versions give the same answer. Timing it is a good Topic 13.7 exercise on your own computer. A realistic version: a million sale amounts where you need amount * 1.18 for each, the loop against one array line.
Vectorisation means writing one array expression instead of a Python loop. Broadcasting is the rule that lets arrays of different shapes combine, by stretching size-1 dimensions to match.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Given prices = np.array([[10.0, 20.0], [30.0, 40.0]]) and tax = np.array([1.05, 1.10]), apply a different tax to each column.
Make a 3-by-3 multiplication table from 1 to 3 using np.arange(1, 4) and broadcasting.
Normalise each row of m = np.array([[1.0, 3.0], [2.0, 2.0]]) so the row sums to 1, using keepdims=True.
Explain it without notes
What is vectorisation and why is it faster than a Python loop?
State the broadcasting rule. Walk through (3, 1) plus (4,).
Why does np.ones((2, 3)) + np.ones((2,)) fail, and how do you fix it?
Where does broadcasting appear in a neural network layer?
Expected output
loop result: 40000000000.0
vector result: 40000000000.0
same: True
sqrt: [0. 1. 2. 3.]
exp(0): [1.]
maximum: [2. 2. 4. 9.]
clip: [1. 1. 4. 5.]