Vectorisation: Letting C Do the Loop

Vectorisation: Letting C Do the Loop in Python: A Python loop over a million numbers is slow for a specific, structural reason.

Concept Explanation

A Python for loop over a million numbers is slow for a specific, structural reason. Every iteration involves a bytecode dispatch, a type check, an integer object allocation, and a reference-count update. The arithmetic is a rounding error compared to the overhead around it.

NumPy moves the loop into compiled C. One call to arr * 2 performs a million multiplications inside a tight machine-code loop over contiguous memory, with no Python objects created at all. The speedup is typically 10× to 100×.

Why Arrays Beat Lists

Python listNumPy array
StoragePointers to scattered objectsOne contiguous block
TypesAnything, per elementOne dtype for all
Per-element overhead~28 bytes + pointer8 bytes (float64)
ArithmeticInterpreted loopCompiled loop, often SIMD

Contiguity matters as much as compilation: the CPU can prefetch the next values into cache, which a list of pointers to objects scattered across the heap cannot do.

The Rule

If you are writing a for loop over a NumPy array, there is almost certainly a vectorised form.

# Slow: interpreted loop
result = []
for x in data:
    result.append(x * 2 + 1)

# Fast: one compiled operation
result = data * 2 + 1

Boolean Masks Replace if-statements

This is the idiom that takes longest to internalise and pays off most:

mask = (prices > 100) & (in_stock)      # a boolean array
prices[mask] *= 0.9                     # modify only those elements
count = mask.sum()                      # True counts as 1

Use &, |, ~ — not and, or, not, which try to convert the whole array to a single bool and raise. And parenthesise: & binds tighter than > in Python.

np.where(condition, a, b) is the vectorised ternary, and it nests for multi-branch logic.

Broadcasting

NumPy stretches smaller arrays across larger ones without copying:

matrix = np.ones((1000, 3))
weights = np.array([0.5, 1.5, 2.0])     # shape (3,)
scaled = matrix * weights               # applies down every row

The rule: compare shapes from the right; dimensions must be equal or one of them must be 1. Adding a None axis is how you control the direction:

col = arr[:, None]      # shape (n, 1) -- a column
row = arr[None, :]      # shape (1, n) -- a row
diffs = col - row       # shape (n, n) -- all pairwise differences

The Functions Worth Knowing

TaskFunction
Conditional valuenp.where(cond, a, b)
Multi-branchnp.select([c1, c2], [v1, v2], default=v3)
Clamp to a rangenp.clip(arr, lo, hi)
Running totalnp.cumsum, np.cumprod
Bin into rangesnp.digitize
Positions of the top knp.argpartition
Group boundariesnp.unique(..., return_counts=True)
Aggregate.sum(), .mean(), .std() with axis=

Watch the Memory

Vectorisation's cost is temporaries: a * b + c * d allocates two intermediate arrays. On a 10 GB dataset that matters. In-place operators (arr *= 2) and the out= parameter avoid the allocation.

When Vectorising Is Not the Answer

df.apply(fn, axis=1) and np.vectorize look vectorised and are not — both loop in Python underneath. np.vectorize's own documentation says it is provided for convenience, not performance. For genuinely element-wise Python logic that cannot be expressed in array operations, use Numba's @njit instead.


Code Example #1 (Basic)

The same computation four ways, measured.

import time
import numpy as np

N = 2_000_000
py_list = list(range(N))
arr = np.arange(N, dtype=np.float64)


def timed(label, fn):
    start = time.perf_counter()
    result = fn()
    elapsed = time.perf_counter() - start
    print(f"{label:<32} {elapsed * 1000:>9.1f} ms")
    return elapsed


# --- Arithmetic over every element ---
t_loop = timed("python for loop",
               lambda: [x * 2.5 + 1 for x in py_list])
t_map = timed("map + lambda",
              lambda: list(map(lambda x: x * 2.5 + 1, py_list)))
t_np = timed("numpy vectorised",
             lambda: arr * 2.5 + 1)
t_inplace = timed("numpy in-place (no temporary)",
                  lambda: np.add(np.multiply(arr, 2.5), 1, out=np.empty_like(arr)))

print(f"\nnumpy is {t_loop / t_np:,.0f}x faster than the loop\n")


# --- Boolean masks instead of if-statements ---
prices = np.random.default_rng(0).uniform(5, 500, 1_000_000)

start = time.perf_counter()
discounted_loop = [p * 0.9 if p > 100 else p for p in prices]
loop_ms = (time.perf_counter() - start) * 1000

start = time.perf_counter()
discounted_np = np.where(prices > 100, prices * 0.9, prices)
np_ms = (time.perf_counter() - start) * 1000

print(f"conditional, list comprehension: {loop_ms:>8.1f} ms")
print(f"conditional, np.where:           {np_ms:>8.1f} ms  ({loop_ms / np_ms:,.0f}x)")
print(f"same result: {np.allclose(discounted_loop, discounted_np)}\n")


# --- Masks: counting, filtering, and modifying in place ---
mask = (prices > 100) & (prices < 400)      # & not 'and'; parentheses required
print(f"items in range:  {mask.sum():,}")
print(f"their mean:      {prices[mask].mean():.2f}")
print(f"fraction:        {mask.mean():.1%}")

copy = prices.copy()
copy[copy > 400] = 400                      # clamp, vectorised
print(f"after clamping, max = {copy.max():.1f}")


# --- Broadcasting ---
matrix = np.ones((4, 3))
weights = np.array([0.5, 1.0, 2.0])         # shape (3,) stretches across rows
print(f"\n(4,3) * (3,) -> {(matrix * weights).shape}")
print(matrix * weights)

col = np.arange(4)[:, None]                 # (4,1)
row = np.arange(3)[None, :]                 # (1,3)
print(f"\n(4,1) + (1,3) -> {(col + row).shape}   -- an outer sum, no loop")
print(col + row)

The out= version avoids allocating a temporary array. On two million float64 values each temporary is 16 MB; in a pipeline of ten operations on a large dataset, that is the difference between fitting in memory and not.

Code Example #2 (Intermediate)

Vectorising a realistic pipeline, plus the traps.

import time
import numpy as np
import pandas as pd

rng = np.random.default_rng(7)
N = 500_000

df = pd.DataFrame({
    "quantity": rng.integers(1, 25, N),
    "unit_price": rng.uniform(2, 400, N).round(2),
    "customer_tier": rng.choice(["bronze", "silver", "gold"], N, p=[.6, .3, .1]),
    "weight_kg": rng.gamma(2, 1.5, N).round(2),
    "express": rng.random(N) < 0.2,
})


# ==================== The slow way: apply(axis=1) ====================
def price_row(row):
    subtotal = row["quantity"] * row["unit_price"]
    if row["customer_tier"] == "gold":
        subtotal *= 0.85
    elif row["customer_tier"] == "silver":
        subtotal *= 0.93
    shipping = 4.99 + max(0.0, row["weight_kg"] - 2) * 1.2
    if row["express"]:
        shipping *= 2.5
    if subtotal > 250:
        shipping = 0.0
    return round(subtotal + shipping, 2)


small = df.head(40_000)
start = time.perf_counter()
slow_result = small.apply(price_row, axis=1)
apply_ms = (time.perf_counter() - start) * 1000
print(f"apply(axis=1) on {len(small):,} rows: {apply_ms:>8.1f} ms")
print(f"  extrapolated to {N:,}: ~{apply_ms * N / len(small) / 1000:.1f} s\n")


# ==================== The fast way: whole-column operations ====================
start = time.perf_counter()

subtotal = df["quantity"].to_numpy() * df["unit_price"].to_numpy()

# Multi-branch logic without any if-statement
tier = df["customer_tier"].to_numpy()
discount = np.select(
    [tier == "gold", tier == "silver"],
    [0.85, 0.93],
    default=1.0,
)
subtotal = subtotal * discount

# max(0, x) vectorised
excess_weight = np.clip(df["weight_kg"].to_numpy() - 2, 0, None)
shipping = 4.99 + excess_weight * 1.2

# Conditional multiply via a boolean mask
shipping = np.where(df["express"].to_numpy(), shipping * 2.5, shipping)

# Free shipping over a threshold
shipping = np.where(subtotal > 250, 0.0, shipping)

fast_result = np.round(subtotal + shipping, 2)
vec_ms = (time.perf_counter() - start) * 1000

print(f"vectorised on {N:,} rows:      {vec_ms:>8.1f} ms")
print(f"  same answers: "
      f"{np.allclose(fast_result[:len(small)], slow_result.to_numpy())}")
print(f"  speedup on equal rows: "
      f"{(apply_ms * N / len(small)) / vec_ms:,.0f}x\n")


# ==================== Grouped statistics without a loop ====================
start = time.perf_counter()
codes, uniques = pd.factorize(df["customer_tier"])
totals = np.bincount(codes, weights=fast_result)      # sum per group, in C
counts = np.bincount(codes)
print("Revenue by tier (np.bincount):")
for name, total, n in zip(uniques, totals, counts):
    print(f"  {name:<8} {n:>7,} orders  {total:>12,.2f}")
print(f"  computed in {(time.perf_counter() - start) * 1000:.1f} ms\n")


# ==================== The traps ====================
print("=== Trap 1: 'and' instead of '&' ===")
a = np.array([1, 5, 9])
try:
    _ = (a > 2) and (a < 8)
except ValueError as exc:
    print(f"  {str(exc)[:68]}...")
print(f"  correct: {(a > 2) & (a < 8)}\n")

print("=== Trap 2: operator precedence ===")
print(f"  a > 2 & a < 8   parses as a > (2 & a) < 8 -- wrong")
print(f"  (a > 2) & (a < 8) = {(a > 2) & (a < 8)}   -- always parenthesise\n")

print("=== Trap 3: views vs copies ===")
base = np.arange(10)
view = base[2:5]                    # a VIEW, sharing memory
view[0] = 999
print(f"  slicing gives a view:  base = {base[:6]}")
base2 = np.arange(10)
copy = base2[2:5].copy()
copy[0] = 999
print(f"  .copy() is independent: base = {base2[:6]}\n")

print("=== Trap 4: np.vectorize is NOT vectorised ===")
def scalar_fn(x):
    return x ** 2 + 1

vec_fn = np.vectorize(scalar_fn)
data = np.arange(200_000, dtype=np.float64)

start = time.perf_counter()
vec_fn(data)
fake_ms = (time.perf_counter() - start) * 1000
start = time.perf_counter()
data ** 2 + 1
real_ms = (time.perf_counter() - start) * 1000
print(f"  np.vectorize:    {fake_ms:>7.1f} ms  (a Python loop in disguise)")
print(f"  real vectorised: {real_ms:>7.1f} ms  ({fake_ms / real_ms:,.0f}x faster)\n")

print("=== Trap 5: dtype and memory ===")
big64 = np.ones(1_000_000, dtype=np.float64)
big32 = np.ones(1_000_000, dtype=np.float32)
print(f"  float64: {big64.nbytes / 1e6:.1f} MB")
print(f"  float32: {big32.nbytes / 1e6:.1f} MB  (half the memory, half the precision)")
ints = np.arange(1_000_000)
print(f"  int64 -> int32 saves {(ints.nbytes - ints.astype(np.int32).nbytes) / 1e6:.1f} MB")

np.select deserves highlighting — it is the vectorised if/elif/else and the piece most people are missing when they conclude "my logic is too complicated to vectorise". Between np.select, np.where, np.clip, and boolean masks, the large majority of row-wise business logic translates directly.


Common Mistakes

  1. Looping over a NumPy array: for x in arr throws away every advantage and is often slower than looping over a list.
  2. and/or on arrays: raises ValueError: truth value of an array is ambiguous. Use &, |, ~.
  3. Forgetting parentheses: a > 2 & a < 8 parses wrongly because & binds tighter than >.
  4. df.apply(fn, axis=1): a Python loop with extra overhead. It is the slowest way to do almost anything in pandas.
  5. Believing np.vectorize vectorises: it does not. It is a convenience wrapper around a loop.
  6. Growing an array in a loop: np.append reallocates the entire array each call. Preallocate with np.empty or build a list and convert once.
  7. Not realising a slice is a view: mutating arr[2:5] changes arr. Use .copy() when you need independence.
  8. Ignoring dtype: float64 when float32 would do wastes half your memory and half your cache bandwidth.
  9. Chained temporaries on huge arrays: a*b + c*d + e*f allocates several full-size intermediates. Use in-place operators or out=.
  10. Mixing dtypes accidentally: one Python float in an int array promotes everything to float64.
  11. Using .iterrows(): it builds a Series object per row. Never appropriate for computation.
  12. Vectorising code that runs once on 50 rows: readability wins when the data is small.

Best Practices

  • Treat any for loop over an array as a bug until you have confirmed no vectorised form exists.
  • Learn np.where and np.select — between them they cover most conditional logic.
  • Use boolean masks for filtering, counting, and conditional assignment; mask.sum() counts and mask.mean() gives the proportion.
  • Always parenthesise comparisons joined by & or |.
  • Preallocate rather than append: np.empty(n) then fill, or build a list and call np.array once.
  • Use in-place operators and out= on large arrays to avoid temporaries.
  • Choose the smallest sufficient dtype — float32 and int32 halve memory and often double throughput.
  • Reach for .to_numpy() inside hot pandas code to skip index alignment overhead.
  • Prefer np.bincount or groupby over manual grouping loops.
  • Verify correctness with np.allclose after vectorising — floating-point results may differ in the last bits.
  • When logic genuinely cannot be vectorised, use Numba's @njit, not np.vectorize.
  • Profile before and after. Vectorised code that is harder to read must earn its place with a measurement.

Practice Exercises

  1. The Loop Elimination: Write a list comprehension applying x * 3 + 7 to a million numbers, then the NumPy equivalent. Time both, report the ratio, and confirm the results match with np.allclose.
  2. The Conditional Rewrite: Take a function with three branches (if/elif/else) applied per row via df.apply(axis=1) and rewrite it using np.select. Time both on 200,000 rows and verify identical output.
  3. The Trap Tour: In one script, demonstrate all four of: and raising on arrays, missing parentheses giving a wrong answer, a slice mutating its parent, and np.vectorize being slower than a real vectorised expression. Print a one-line explanation with each.