Why NumPy
Pure-Python loops are 100× slower than NumPy for numeric work. Here's why — and how to think in vectorized operations.
What you'll learn
- ✓ Why NumPy is faster than equivalent Python loops
- ✓ The mental shift from element-wise loops to whole-array operations
- ✓ How vectorization sets up everything in Pandas, scikit-learn, and PyTorch
NumPy is the array library that sits underneath Pandas, scikit-learn, PyTorch, JAX, and basically every Python data tool. If you understand NumPy, every other library makes more sense.
The problem with Python lists
Python is dynamic — every number in a list carries type info, reference count, and lives at its own memory address. To add two lists of a million numbers, the interpreter loops through them one element at a time, doing Python-level dispatch on each addition.
NumPy stores numbers in a contiguous block of memory, all the same type, and runs operations in compiled C that processes them in tight loops the CPU can vectorize.
The result is typically 10-100× faster, often more.
(click Run)The numbers vary between machines, but NumPy will be 20–100× faster than the list version. That gap widens as N grows.
Think in arrays, not elements
The big mental shift: stop writing for x in arr. Express what you want
on the whole array at once.
(click Run)That last line — revenue[revenue > 20] — is boolean indexing. The
comparison returns a boolean array; using it as an index picks the rows
where it’s True. This is how almost every filter in Pandas works under
the hood.
Vectorization isn’t just about speed
It’s also more readable. Compare:
# Loop version
out = []
for x, y in zip(prices, qty):
if x * y > 20:
out.append(x * y)
vs.
# Vectorized version
rev = prices * qty
out = rev[rev > 20]
The second version is shorter, has no off-by-one risks, and runs in machine code. After a few weeks of writing NumPy, the loop version will look slow to you.
Quick check
✦ Quick check
0/2 answeredNext
Now that you see why NumPy matters, the next lesson goes into the
ndarray itself — shape, dtype, strides — the things you need to know to
debug array bugs.
Finished the lesson?
Mark it complete to track your progress and keep your streak alive. +20 XP