NumPy: arrays at speed
- Create NumPy arrays from Python lists
- Perform vectorized arithmetic that runs 100× faster than Python loops
- Index and slice multi-dimensional arrays
- Compute statistics with
np.mean,np.std,np.histogram
Pandas, scikit-learn, PyTorch tensors, and every quant/ML stack sit on numpy's ndarray and its C-level broadcasting. The staff-level skill is spotting Python-level for loops over arrays and rewriting them as vectorized ufuncs — often a 100-1000× speedup and a memory-contiguous win for downstream BLAS calls.
- Iterating with
for x in arr— kills the point of numpy; use vectorized ops ornp.vectorizeonly as a last resort. - Mixing dtypes silently — an
int64array + Python float upcasts tofloat64and doubles memory. - Assuming slices are copies —
arr[1:3]is a view; mutating it edits the original. Use.copy()when needed.
NumPy gives you arrays — typed, contiguous, blazing fast.
Why it matters
- Operations are vectorized —
xs * xsruns in C, not Python. - One million points: pure Python takes seconds. NumPy: milliseconds.
Pyodide magic
The first time you run import numpy, the worker auto-downloads NumPy from the CDN.
After that, it's cached in your browser.
Try it
- Bump the sample size to 5 million. Notice the run still finishes quickly.
- Add a histogram:
np.histogram(xs, bins=20)and print the counts.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Import
numpy as np. Create an arrayafrom the list[10, 20, 30, 40, 50]. Print its sum. Expected:150. - Exercise 2
Seed with
np.random.seed(42)and create an array of 1000 random floats vianp.random.rand(1000). Print the mean rounded to 3 decimals. With seed 42 the answer is deterministic — expected:0.487. - Exercise 3
Create an array of the integers 1..12 with
np.arange, reshape it into a 3×4 matrix, and print it. Expected first row shows[1 2 3 4].