Vectorization
14 min
Vectorization means applying an operation to an entire array at once,
instead of writing a Python for loop over its elements. It's both
shorter to write and dramatically faster — NumPy pushes the actual looping
down into compiled C code operating on contiguous memory, skipping
Python's per-element interpreter overhead entirely.
import numpy as np
nums = np.array([1, 2, 3, 4, 5])
doubled = nums * 2 # [2, 4, 6, 8, 10] — no loop written
squared = nums ** 2 # [1, 4, 9, 16, 25]
This one line replaces a loop that would compute (today - yesterday) / yesterday for every pair of consecutive days — a pattern you'll reuse constantly once you get to the Time Series and Quant courses.
The rule of thumb once you're working with NumPy: if you're writing a
Python for loop over array elements to do arithmetic, there's almost
always a vectorized equivalent that's both shorter and 10-100x faster on
real-sized data.
# Don't do this:
result = []
for x in nums:
result.append(x * 2)
# Do this instead:
result = nums * 2
Comparisons and boolean logic vectorize too — nums > 3 returns an array
of True/False, not a single value, which is the foundation of the
boolean masking you'll use in the Indexing & Slicing module.
Write `square_all(nums)`, returning the element-wise square of `nums` as a NumPy array. Use `arr ** 2` — no Python-level loop.
Write `elementwise_add(a, b)`, returning the element-wise sum of two equal-length lists as a NumPy array. Use `+`, not `zip` and a loop.
Why is `arr * 2` on a NumPy array much faster than `[x * 2 for x in list]` on a Python list, for large inputs?
You can replace an element-wise Python loop with a vectorized NumPy expression, and understand why that's faster, not just shorter.