Foundations to Frontier
Tests
C. Programming, Tools and HPC › C1 Python for Science

NumPy: Arrays, Broadcasting, Vectorization and Indexing

NumPy is the foundation of scientific Python: an ndarray is a typed, contiguous memory buffer described by a shape and strides, and whole-array operations run in compiled loops instead of the interpreter. This topic covers creating arrays and dtypes, vectorized arithmetic and ufuncs, reductions along axes, broadcasting rules, basic slicing (views) vs fancy and boolean indexing (copies), einsum, and memory layout. In the exercises you vectorize pairwise distances, robust outlier cleaning and batched rotations, then measure 40–400× speedups over Python loops and the cache cost of strided memory access.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

One instruction, a million numbers

A Python list of numbers is like a pile of separate boxes, each with a label saying “I’m a number”. A NumPy array is a single egg carton: a block of memory holding numbers of one type side by side. Instead of telling the computer “take box 1, add 2, take box 2, add 2, …”, you say “add 2 to the whole carton”, and NumPy does it in fast compiled code, often 100 times faster. Thinking in whole arrays instead of loops is called vectorization.

Inside an ndarray: buffer, shape, strides, views and copies
memory buffer of a = np.arange(12).reshape(3, 4) (one cell = 8 bytes)
0
1#0
2
3
4
5#1
6
7
8
9#2
10
11
result as seen through its shape
1
5
9
shape=(3) strides=(32) offset=8B · VIEW · non-contiguous
Element (i, j) lives at byte offset + i·stride₀ + j·stride₁. Slicing, transposing, reversing and most reshapes just change shape/strides/offset: an O(1) view, and writing to it changes a. Fancy (integer-array) and boolean indexing can't be expressed with strides, so NumPy copies. Non-contiguous views are slower to traverse (cache lines are wasted) and some functions copy them internally.
Why engineers care

Everything numerical in Python — trajectory propagation, image processing, sensor fusion, the tensors in PyTorch and JAX — follows NumPy’s array model. Vectorized code runs telemetry analyses in milliseconds instead of minutes, and understanding views, copies and memory layout prevents both silent bugs and huge slowdowns.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A NumPy array stores…
  2. 2. Vectorization means…
  3. 3. x * 2 on an array of a million floats runs…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

Creating and inspecting arrays

import numpy as np
a = np.array([[1.0, 2.0], [3.0, 4.0]])   # dtype float64, shape (2, 2)
np.zeros((3, 4)); np.ones(5); np.arange(0, 1, 0.1); np.linspace(0, 1, 11)
rng = np.random.default_rng(42); x = rng.standard_normal(1000)
a.shape, a.ndim, a.dtype, a.size, a.nbytes

Element-wise operations and reductions

+ - * / **, comparisons, and ufuncs (np.sin, np.exp, np.sqrt) apply element by element. Reductions collapse an axis: a.sum(), a.sum(axis=0) (down columns), a.mean(axis=1) (across rows), a.max(), a.argmax(), np.cumsum.

Indexing

  • Basic: a[i, j], slices a[1:, ::2] (these are views).
  • Boolean: x[x > 3] selects matching elements (a copy).
  • Fancy: a[[0, 2]] uses integer arrays (a copy).
📝 Quick check (Level 1)
0/3 answered
  1. 1. np.arange(12).reshape(3, 4).sum(axis=0) has shape…
  2. 2. x[x > 0] returns…
  3. 3. np.linspace(0, 1, 11)[3] is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Broadcasting

Shapes are aligned from the right; each pair of dimensions must be equal or one of them must be 1 (which is stretched without copying). Missing leading dimensions count as 1.

P[:, None, :] - Q[None, :, :]     # (n,1,3) − (1,m,3) → (n,m,3): all pairwise differences
(A - A.mean(0)) / A.std(0)        # (n,k) with (k,): column-wise standardization

einsum

np.einsum("nij,nj->ni", R, v) applies n different matrices to n vectors in one call. Repeated indices are summed. It expresses batched matrix products, traces and contractions compactly.

Vectorization patterns

  • Replace loops over elements with whole-array expressions.
  • Replace running sums with cumsum (moving averages in O(n)).
  • Replace if/else with np.where(cond, a, b) or masks.
  • Replace loops over pairs with broadcasting, watching the O(nm) memory.
🐍 Exercise 1: vectorize real computations
Write loop-free NumPy code for pairwise distances (broadcasting) and nearest neighbours, robust outlier cleaning with the median and MAD (masks), rotating n points by n different angles (stacked matrices + einsum), column standardization, and a test of whether two arrays share memory (views vs copies).
📝 Quick check (Level 2)
0/3 answered
  1. 1. Shapes (5, 1, 3) and (4, 3) broadcast to…
  2. 2. Shapes (3, 4) and (3,)…
  3. 3. A moving average in O(n) without loops uses…

Level 3: Advanced

★★★★☆ Advanced⏱ 35 minGraduate level, with full derivations and proofs.

The ndarray model

An array is (buffer, dtype, shape, strides, offset). Element (i, j) is at offset + i*strides[0] + j*strides[1] bytes. Slicing, transposing and reversing only change strides and offset, which is why they are O(1) views. A view is C-contiguous when the last stride equals the item size and each earlier stride is the product of later sizes. Fancy and boolean indexing can’t be expressed with strides, so they copy.

Why vectorized code is fast

  1. The loop runs in C over raw doubles: no boxing, type dispatch or reference counting per element.
  2. Contiguous data streams through caches and SIMD units.
  3. Some operations (matmul, FFT) call highly tuned libraries (BLAS, pocketfft).

Strided access defeats point 2: memory moves in 64-byte cache lines (8 doubles). With stride 16 (128 bytes) every element needs its own line, and 7/8 of each transferred line is wasted.

Pitfalls

  • Views alias their base: after b = a[:3], writing b[0] = 99 also changes a. Call .copy() when you need independent data. (NumPy does detect overlapping inputs and outputs of a single ufunc call and buffers them, so a[1:] += a[:-1] is computed as if from a copy.)
  • Integer overflow: int32 arrays wrap silently.
  • Float comparisons: use np.allclose.
  • Big temporaries: broadcasting n × m × d intermediates can exhaust memory; chunk the computation or use scipy.spatial.cKDTree.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Strides of a C-ordered float64 array of shape (3, 4):
  2. 2. a.T of that array has strides…
  3. 3. Why is a[::16].sum() slow per element?

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Vectorization, measured

Exercise 2. Speedup of NumPy over plain-Python loops (typical over several runs; the NumPy side is timed with a calibrated loop because a single call lasts only ~0.1 ms):

kernel CPython Pyodide
moving average (k = 20), loop over windows vs cumsum ≈ 330–410× ≈ 570×
row norms of 50 000 × 3 points ≈ 42–48× ≈ 50×
cubic polynomial on 200 000 values ≈ 100–125× ≈ 120×

Summing 250 000 float64 values taken with stride s costs about 0.11–0.15, 0.15–0.18, 0.23–0.31, 0.5–0.6 and 1.6–1.7 ns per element for s = 1, 2, 4, 8 and 16 (CPython and Pyodide agree closely): about 11–15× slower at stride 16, purely from memory access.

A lesson from building this exercise: a first version timed single calls, and in the browser the sums at small strides came out as 0.00 ns. Browsers deliberately coarsen their clocks (to ~0.1 ms or worse), so short operations must be repeated in a calibrated loop before timing.

🐍 Exercise 2 (research): how fast is vectorized, and what does memory layout cost?
Time Python-loop and NumPy versions of three kernels (checking that results agree), compute the speedups, then measure the time per element of summing an array with increasing stride.

NumPy in AI, robotics and aerospace

  • Batch processing of telemetry, images and point clouds with masks, broadcasting and einsum.
  • Kinematics and attitude with stacks of rotation matrices or quaternions.
  • The array model behind PyTorch and JAX tensors (C3): the same shapes, broadcasting, strides and views.
  • Performance engineering: contiguous layouts and avoiding temporaries matter on embedded and HPC systems alike (C5).

References

  1. C. R. Harris et al. (2020). “Array programming with NumPy.” Nature, 585.
  2. NumPy documentation: Broadcasting, Indexing on ndarrays, Internal organization of NumPy arrays (numpy.org/doc).
  3. J. VanderPlas (2016). Python Data Science Handbook. O’Reilly (chapter 2).
  4. S. van der Walt, S. C. Colbert, G. Varoquaux (2011). “The NumPy array: a structure for efficient numerical computation.” Computing in Science & Engineering, 13(2).
  5. U. Drepper (2007). “What every programmer should know about memory.” Red Hat.