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.
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.
- 1. A NumPy array stores…
- 2. Vectorization means…
- 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.nbytesElement-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], slicesa[1:, ::2](these are views). - Boolean:
x[x > 3]selects matching elements (a copy). - Fancy:
a[[0, 2]]uses integer arrays (a copy).
- 1. np.arange(12).reshape(3, 4).sum(axis=0) has shape…
- 2. x[x > 0] returns…
- 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 standardizationeinsum
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.
- 1. Shapes (5, 1, 3) and (4, 3) broadcast to…
- 2. Shapes (3, 4) and (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
- The loop runs in C over raw doubles: no boxing, type dispatch or reference counting per element.
- Contiguous data streams through caches and SIMD units.
- 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], writingb[0] = 99also changesa. Call.copy()when you need independent data. (NumPy does detect overlapping inputs and outputs of a single ufunc call and buffers them, soa[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.
- 1. Strides of a C-ordered float64 array of shape (3, 4):
- 2. a.T of that array has strides…
- 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.
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
- C. R. Harris et al. (2020). “Array programming with NumPy.” Nature, 585.
- NumPy documentation: Broadcasting, Indexing on ndarrays, Internal organization of NumPy arrays (numpy.org/doc).
- J. VanderPlas (2016). Python Data Science Handbook. O’Reilly (chapter 2).
- 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).
- U. Drepper (2007). “What every programmer should know about memory.” Red Hat.