Part 01 / Topic 3 of 7
Vectorization
Vectorization means expressing a computation as whole-array operations instead of a Python loop. The loop still happens — but in compiled C over contiguous memory, not one interpreted Python step per element.
Real-world example: Revenue over a million sales — a dot product of prices and quantities.
# examples/01_vectorized_numpy_gives_the_same_answer.py
import time
import numpy as np
rng = np.random.default_rng(0)
prices = rng.uniform(10, 100, size=1_000_000)
qty = rng.integers(1, 5, size=1_000_000)
t0 = time.perf_counter()
total_loop = 0.0
for p, q in zip(prices, qty):
total_loop += p * q
t_loop = time.perf_counter() - t0
t0 = time.perf_counter()
total_vec = float(np.dot(prices, qty))
t_vec = time.perf_counter() - t0
print("same answer:", np.isclose(total_loop, total_vec))
print("vectorized is faster:", t_vec < t_loop)
# same answer: True
# vectorized is faster: True
On this machine the vectorized version was two orders of magnitude faster. The exact speedup varies; the ranking never does.
🧪 Quick quiz
- Why is
np.dot(prices, qty)much faster than a Pythonforloop over the same arrays?
Show the answer
The loop body runs in compiled code over contiguous memory instead of one Python step per element. (No GPU involved — NumPy runs on the CPU.)
Done here? The practice set for Part 1 — 4 exercises with solutions — is on the part page.