Sub topic 11
Moving loops into NumPy
This chapter assumes you can write Python loops and functions, have installed packages with pip, and have already profiled a program to find a hot loop. If you have not, go back to the chapters on timing and cProfile first.
Why a loop is slow in Python
A Python for loop does extra work on every pass. The interpreter looks up the type of each object, dispatches the operation, and creates a new Python object for the result. When the loop body is tiny, such as total += i * i, this overhead costs more than the arithmetic.
Vectorization means handing a whole array to one function call. NumPy runs the loop inside compiled code, on values stored in one contiguous block of memory. You write no loop, and the per-item overhead drops sharply.
Install NumPy with pip install numpy.
The core idea
This is the vectorized example from the plan:
import numpy as np
values = np.arange(1_000_000, dtype=np.int64)
total = int((values * values).sum())
print(total)values * values multiplies the arrays element by element in compiled code. .sum() adds the products, also in compiled code. Neither step runs a Python loop. The dtype=np.int64 argument matters here. The sum of squares below one million is about 3.3 × 10^17, which fits in 64 bits. A 32-bit integer would overflow without warning.
Comparing loop and vectorized versions
Measure the gain with time.perf_counter, as in the timing chapter. This script also checks that both versions agree.
import time
import numpy as np
N = 1_000_000
def loop_version(n):
total = 0
for i in range(n):
total += i * i
return total
def numpy_version(n):
values = np.arange(n, dtype=np.int64)
return int((values * values).sum())
start = time.perf_counter()
a = loop_version(N)
loop_time = time.perf_counter() - start
start = time.perf_counter()
b = numpy_version(N)
numpy_time = time.perf_counter() - start
assert a == b
print(f"loop: {loop_time:.4f}s")
print(f"numpy: {numpy_time:.4f}s")On typical hardware the NumPy version is tens of times faster. The exact ratio depends on your machine, so run it yourself and trust your numbers.
Operations you will use most
| Task | Loop style | NumPy style |
|---|---|---|
| Element-wise math | `[x * 2 for x in xs]` | `arr * 2` |
| Filter | `[x for x in xs if x > 0]` | `arr[arr > 0]` |
| Conditional value | `x if x > 0 else 0` per item | `np.where(arr > 0, arr, 0)` |
| Total | `sum(xs)` | `arr.sum()` |
| Pairwise combine | `[a + b for a, b in zip(xs, ys)]` | `a_arr + b_arr` |
A comparison such as arr > 0 produces a boolean array. You can use that array as a mask to select items, or pass it to np.where.
How the data flows
Common errors
- Converting inside the loop. Calling
np.array(...)on small lists repeatedly costs more than it saves. Convert once, then do all the work on the array. - Looping over an array in Python.
for x in arr:is often slower than looping over a list, because each item becomes a NumPy scalar object. If you must loop, usearr.tolist()first. - Integer overflow. Fixed-width integers wrap around silently. Choose a
dtypethat fits your largest result. - Memory use. Each intermediate expression such as
values * valuesallocates a full array. On very large data, this can be a bigger cost than the time. Check it withtracemallocor by watching process memory. Note thattracemalloctracks NumPy data buffers in recent NumPy versions, but confirm this on your version. - Small data. For arrays of a few dozen items, call overhead can dominate and a plain loop may win. Always time both.
When vectorization does not fit
Some loops depend on the previous iteration, for example a running state that changes in a data-dependent way. These resist vectorization. Many cases still have a built-in, such as np.cumsum for running totals. For the rest, the native code chapter covers Numba and Cython.
Exercise
A profile shows that def count_positive(xs): return sum(1 for x in xs if x > 0) is your hot spot, and xs is a list of 5 million floats that you will reuse for many calls. Rewrite it using NumPy, say where the conversion should happen, and name one thing you must still verify.
Show answer
Convert once, outside the function: arr = np.array(xs). Then use def count_positive(arr): return int((arr > 0).sum()). The comparison builds a boolean array and the sum counts the True values. Converting on every call would waste the gain. You must still time both versions with perf_counter or timeit on your own data and check that the two results are equal.
Exercise
Why can for x in arr: over a NumPy array be slower than the same loop over a list?
Show answer
Each pass creates a NumPy scalar object from the array's raw memory, which costs more than reading a Python object that already exists in a list. NumPy is fast only when its compiled loops do the iteration.