Sub topic 11
Moving loops into NumPy
This chapter assumes you can time code with perf_counter and timeit, read a cProfile report, and install packages with pip. Run pip install numpy before the examples. The profiling chapters showed you how to find a hot loop. Here you will learn one of the most effective fixes for loops that do arithmetic over many numbers.
Why a Python loop is slow
Each pass through a Python for loop does extra work. The interpreter fetches the next object and checks the types of the operands. It looks up the right addition or multiplication method, creates a new result object, and updates reference counts. For one multiplication, that overhead is far larger than the multiplication itself.
A NumPy array avoids most of this. It stores numbers of one type (such as int64) in a single block of memory. An operation like values * values runs one compiled loop over that block and does no per-item type checks. Moving a loop out of Python and into such a compiled routine is called vectorization.
import numpy as np
values = np.arange(1_000_000, dtype=np.int64)
total = int((values * values).sum())
print(total)The squaring and the summing both run in compiled NumPy loops. The Python code only makes two calls.
Measure the gain
Do not assume the vectorized version is faster. Time both with timeit, and check that they give the same answer first.
import timeit
import numpy as np
values = np.arange(1_000_000, dtype=np.int64)
py_list = values.tolist()
def loop_sum(data):
total = 0
for v in data:
total += v * v
return total
def vec_sum(arr):
return int((arr * arr).sum())
assert loop_sum(py_list) == vec_sum(values)
loop_time = timeit.timeit(lambda: loop_sum(py_list), number=5)
vec_time = timeit.timeit(lambda: vec_sum(values), number=5)
print(f"python loop: {loop_time:.3f}s")
print(f"numpy: {vec_time:.3f}s")
print(f"speedup: {loop_time / vec_time:.0f}x")On typical hardware the NumPy version is tens of times faster for an array this size. The exact ratio depends on your machine, so report your own number. The test data is built outside the timed functions, so the comparison measures only the computation.
Thinking in whole arrays
Vectorizing means rewriting what the loop does as operations on whole arrays. Four tools cover most cases.
Element-wise operations
Arithmetic operators and functions such as np.sqrt, np.exp, and np.abs apply to every element. They are called universal functions (ufuncs). Replace [math.sqrt(x) for x in xs] with np.sqrt(xs). The math functions only accept single numbers, so they cannot be used on arrays.
Broadcasting
Broadcasting lets NumPy combine arrays of different shapes. It stretches the smaller array across the larger one without copying data. The shapes must be compatible: compared from the last dimension backward, each pair of sizes must be equal or one of them must be 1.
import numpy as np
data = np.array([[1.0, 2.0, 3.0],
[4.0, 5.0, 6.0],
[7.0, 8.0, 9.0]])
col_means = data.mean(axis=0) # shape (3,)
centered = data - col_means # (3, 3) minus (3,) broadcasts per row
print(col_means)
print(centered)The shape (3,) array is subtracted from every row of the (3, 3) array. A nested loop over rows and columns is not needed.
Boolean masks and np.where
Comparisons produce arrays of True and False. You can use them to select elements or to choose between two results.
import numpy as np
prices = np.array([12.5, 80.0, 45.0, 3.2, 99.9])
expensive = prices > 50
print(prices[expensive].sum())
sale = np.where(prices > 50, prices * 0.9, prices)
print(sale)This replaces a loop with an if inside it. Note that np.where computes both branches for every element and then picks one. That is fine for cheap expressions, but wasteful if one branch is expensive.
Reductions and the axis argument
Methods such as sum, mean, max, and argmax collapse an array. The axis argument chooses which dimension to collapse. axis=0 collapses rows and gives one result per column. axis=1 gives one result per row.
Where vectorization stops paying off
The diagram shows a quick way to decide whether a loop can be moved into NumPy.
Several situations reduce or remove the benefit:
- Small arrays. Each NumPy call has a fixed cost of a few hundred nanoseconds to microseconds. For an array of ten items, a plain loop can be just as fast or faster.
- Conversion cost.
np.array(some_list)has to inspect and copy every item. If you convert a list, do one operation, and convert back, you may lose the gain. Keep data in arrays between steps. - Sequential dependencies. If step
ineeds the result of stepi - 1in a way no built-in expresses, the loop cannot be vectorized directly. - Non-numeric data. Arrays of Python objects, such as strings of different lengths or dicts, run at Python speed.
- np.vectorize. Despite the name,
np.vectorizeis a convenience wrapper that still calls your Python function once per element. It makes code shorter but not faster.
Edge cases that cause wrong answers
Speed means nothing if the result changes. Watch for these.
Silent integer overflow
NumPy integers have a fixed size. Array arithmetic that exceeds the range wraps around without an error.
import numpy as np
a = np.array([2_000_000_000, 2_000_000_000], dtype=np.int32)
print(a + a) # wraps to negative values
print(a.astype(np.int64) + a) # correctPython's own int never overflows, so a loop-to-NumPy rewrite can change results. The first example used int64 and a million items. The largest square there is about 10^12, and the total is about 3.3 × 10^17, which fits in int64 (limit about 9.2 × 10^18). Larger inputs would not fit, so check the range for your data.
Floating-point order
arr.sum() adds numbers in a different order than a Python loop does. NumPy uses pairwise summation, which is usually more accurate, but the last digits can differ. Compare floating-point results with np.allclose, not ==.
Views versus copies
Basic slices such as arr[2:5] return views that share memory with the original. Writing to a view changes the original array. Boolean masks and fancy indexing return copies. Call .copy() when you need independence.
Memory cost of temporaries
An expression like a * b + c creates a full-size temporary array for a * b before adding c. For huge arrays this doubles memory use and adds allocation time. The out argument writes results into an array you already have.
import numpy as np
values = np.arange(1_000_000, dtype=np.int64)
buffer = np.empty_like(values)
np.multiply(values, values, out=buffer)
print(int(buffer.sum()))Use tracemalloc or a memory profiler (see the earlier chapter) to confirm the temporary matters before rewriting code this way. NumPy allocations are tracked by tracemalloc, so you can compare peak memory for both versions.
Comparing the approaches
| Approach | Strength | Weakness |
|---|---|---|
| Python loop | Works on any data, easy to debug | Per-item interpreter overhead |
| List comprehension | Somewhat faster than a plain loop | Still runs at Python speed per item |
| NumPy vectorization | Large speedups on numeric arrays | Needs uniform dtype, creates temporaries |
| Numba or Cython | Handles dependent loops | Extra tooling, covered in a later chapter |
A workflow to follow
- Profile and confirm the loop is the hot spot.
- Write a test that stores the loop's output for a sample input.
- Rewrite with array operations and compare outputs, using
np.allclosefor floats. - Time both versions with realistic data sizes.
- Check dtypes and value ranges for overflow.
Exercise
A function counts how many readings in a Python list readings exceed a threshold, using a for loop with an if. Show a vectorized version, and name one reason it might not be faster for a list of 20 items.
Show answer
Convert once and use a mask: arr = np.asarray(readings) then count = int((arr > threshold).sum()). For 20 items, the fixed cost of each NumPy call and of converting the list to an array can be larger than the time the plain loop takes, so the loop may be as fast or faster. Time both with timeit on realistic sizes.
Exercise
You sum np.array([100_000, 100_000, 100_000], dtype=np.int16) after multiplying each item by 1000, and get a surprising result. What happened, and how do you fix it?
Show answer
The products are 100,000,000, far above the int16 maximum of 32,767, so the values wrapped around silently. (The initial values already do not fit in int16 either.) Use a larger dtype such as np.int64 when creating the array, or cast with astype(np.int64) before multiplying.