Skip to content

Lesson 42 of 59Libraries every Python developer knows

NumPy Essentials

Work with NumPy arrays, vectorised maths, shapes, broadcasting and boolean masks, and understand why NumPy is so much faster than lists.

17 min read0/5 questions

Sooner or later a backend touches numbers in bulk: scoring search results, computing statistics for a dashboard, preparing features for a model, resizing an image. A Python loop over a million values works, but it is slow. NumPy stores numbers in compact arrays and runs whole operations in compiled C, which is often 10 to 100 times faster. It is also the foundation that pandas, scikit-learn, PyTorch and most of the data ecosystem build on, so its ideas (shapes, broadcasting, masks) show up everywhere.

Arrays versus lists

Install it with uv add numpy and import it under the alias everyone uses:

import numpy as np
 
prices = np.array([19.99, 5.49, 120.00, 42.50])
print(prices.dtype)     # float64
print(prices.shape)     # (4,)
print(prices * 1.2)     # [ 23.988   6.588 144.     51.   ]

An array looks like a list but behaves very differently:

  • One type for every element, called the dtype: int64, float64, bool and so on. Mixing ints and floats upcasts everything to floats.
  • A fixed size. There is no append that grows the array in place. np.append builds a new array, so build a list first and convert it once.
  • Arithmetic applies element by element. prices * 1.2 multiplies every price. With a list, [1, 2] * 2 repeats the list to [1, 2, 1, 2].

Useful ways to create arrays:

np.zeros(5)                  # [0. 0. 0. 0. 0.]
np.ones((2, 3))              # 2 rows, 3 columns of 1.0
np.arange(0, 10, 2)          # [0 2 4 6 8], like range
np.linspace(0, 1, 5)         # [0.   0.25 0.5  0.75 1.  ], 5 evenly spaced points
np.array([[1, 2], [3, 4]])   # a 2D array from nested lists

You can pick the dtype yourself, and it matters more than it looks. np.array([1, 2, 3], dtype=np.float32) uses 4 bytes per value instead of 8. arr.astype(np.int64) converts, always producing a new array. Converting floats to ints truncates toward zero, so np.array([2.7, -2.7]).astype(int) gives [ 2 -2], not a rounded result; call np.round first if you want rounding. Strings and mixed Python objects end up with dtype object, which stores pointers like a list and loses all of NumPy's speed. If you see dtype=object in numeric code, something upstream went wrong.

Why it is fast

A Python list of numbers is really a list of pointers. Each number is a full Python object somewhere else in memory, with a type, a reference count and the value itself. Adding two lists means, for every element, following pointers, checking types and creating a new object. That is the interpreter overhead from the "How Code Runs" lesson, paid a million times.

A NumPy array is one contiguous block of raw numbers, all the same type, with no per-element objects. a + b makes a single call into a C loop that walks both blocks and writes a third. The CPU can stream memory efficiently and often process several numbers per instruction (SIMD). This style is called vectorisation: you describe the operation on the whole array and let compiled code do the loop.

You can see the memory difference with the standard library's array module, which stores raw numbers the same way:

Pythonmemory_layout.py
import sysfrom array import array n = 100_000as_list = [float(i) for i in range(n)]as_array = array("d", as_list) # "d" = 8-byte floats in one block, like float64 list_bytes = sys.getsizeof(as_list) + sum(sys.getsizeof(x) for x in as_list)array_bytes = sys.getsizeof(as_array) print(f"list of floats: {list_bytes / 1e6:.1f} MB (pointers + one object per number)")print(f"packed array: {array_bytes / 1e6:.1f} MB (raw 8-byte values)")print(f"ratio: {list_bytes / array_bytes:.1f}x")
Output
Press Run (⌘ Enter) to see what happens.

The lesson for daily work: avoid Python loops over array elements. If you write for x in arr: you have thrown away the speed. Look for the vectorised version instead.

# Slow: a Python loop, one element at a time
totals = np.array([q * p for q, p in zip(quantities, prices)])
 
# Fast: one vectorised expression
totals = quantities * prices

Shapes, axes and reshape

An array's shape is a tuple of its sizes in each dimension. A 2D array of 3 rows and 4 columns has shape (3, 4). Each dimension is an axis: axis 0 runs down the rows, axis 1 runs across the columns.

a = np.arange(12)            # shape (12,)
grid = a.reshape(3, 4)       # shape (3, 4), the same 12 numbers
print(grid)
# [[ 0  1  2  3]
#  [ 4  5  6  7]
#  [ 8  9 10 11]]
 
grid.reshape(-1)             # back to 1D; -1 means "work this size out"
grid.T                       # transpose, shape (4, 3)

Aggregations take an axis argument that says which axis to collapse:

grid.sum()           # 66, everything
grid.sum(axis=0)     # [12 15 18 21], down each column
grid.sum(axis=1)     # [ 6 22 38], across each row
grid.mean(), grid.max(), grid.std(), grid.argmax()   # argmax: index of the largest

A handy rule: the axis you name disappears from the shape. (3, 4) summed over axis 0 gives (4,).

Predict the outputPython

What does this print?

grid = np.arange(6).reshape(2, 3)   # [[0 1 2] [3 4 5]]
print(grid.sum(axis=1))
Need a nudge? Hints walk you through it.

Broadcasting

Broadcasting is how NumPy combines arrays of different shapes without copying data. prices * 1.2 already used it: the single number is "stretched" to match the array. The same works between arrays. Compare shapes from the right: two dimensions are compatible if they are equal or one of them is 1. Size-1 dimensions stretch to match.

scores = np.array([[70, 80, 90],
                   [60, 75, 85]])        # shape (2, 3): 2 students, 3 tests
weights = np.array([0.2, 0.3, 0.5])     # shape (3,): one weight per test
 
weighted = scores * weights              # (2, 3) * (3,) -> (2, 3)
print(weighted.sum(axis=1))              # [83. 77.] final grade per student
Broadcasting a row of weights across every student
test 1test 2test 3total
student A708090
student B607585

scores has shape (2, 3): one row per student, one column per test.

1/4

Broadcasting also catches mistakes. Shapes (2, 3) and (2,) do not line up from the right (3 versus 2), so NumPy raises ValueError: operands could not be broadcast together. To apply one value per row, give it shape (2, 1), for example with offsets.reshape(-1, 1) or offsets[:, np.newaxis].

Quick check
What is the shape of np.zeros((3, 1)) + np.zeros(4)?
Need a nudge? A hint rules out a wrong answer.

Indexing, slicing and boolean masks

Indexing works like lists, with a comma between dimensions:

grid[0, 2]        # row 0, column 2 -> 2
grid[1]           # the whole second row
grid[:, 0]        # the whole first column
grid[1:, ::2]     # rows from 1 on, every second column

One important difference: a slice is a view, not a copy. Changing grid[0, :] changes grid. That saves memory, but it can surprise you. Call .copy() when you need an independent array.

The feature you will use most is the boolean mask. A comparison produces an array of True/False, and indexing with it keeps only the True positions:

latency_ms = np.array([120, 85, 950, 40, 1300, 210])
 
slow = latency_ms > 500          # [False False  True False  True False]
print(latency_ms[slow])          # [ 950 1300]
print(slow.sum())                # 2, True counts as 1
print(slow.mean())               # 0.333..., the share of slow requests
 
# Combine conditions with & and |, with parentheses around each
mid = latency_ms[(latency_ms > 50) & (latency_ms < 500)]
 
# Replace values without a loop
capped = np.where(latency_ms > 1000, 1000, latency_ms)

Use &, | and ~ for "and", "or" and "not" on arrays, not the Python keywords. a > 1 and a < 5 raises an error, because Python asks for a single truth value of a whole array.

Predict the outputPython

What does this print?

a = np.array([3, 8, 1, 9, 4])
print(a[a > 3].sum())
Need a nudge? Hints walk you through it.

Random numbers

Use a Generator created with np.random.default_rng. Pass a seed when you need repeatable results, such as in tests or experiments.

rng = np.random.default_rng(seed=42)
 
rng.integers(1, 7, size=10)            # ten dice rolls, 1 to 6
rng.normal(loc=100, scale=15, size=5)  # five values from a normal distribution
rng.choice(["a", "b", "c"], size=3)    # random picks
rng.shuffle(items)                      # shuffle in place

You will see older code call np.random.seed(...) and np.random.rand(...). That global style still works, but the Generator is the recommended API: it is faster, statistically better, and each part of your code can own its own generator instead of sharing hidden global state.

Where NumPy shows up in a backend

The most common place today is embeddings. A search or recommendation feature turns each document into a vector of, say, 384 floats, and finds the documents closest to a query. With NumPy that is a few lines and no loop over documents:

app/search.py
docs = np.load("doc_vectors.npy")        # shape (10_000, 384), one row per document
query = embed("cheap flights to Oslo")   # shape (384,)
 
# Cosine similarity: dot products divided by vector lengths
docs_norm = docs / np.linalg.norm(docs, axis=1, keepdims=True)
query_norm = query / np.linalg.norm(query)
scores = docs_norm @ query_norm          # shape (10_000,), one score per document
 
top5 = np.argsort(scores)[-5:][::-1]     # indices of the five best matches

@ is matrix multiplication, broadcasting does the division per row, and argsort ranks the results. For a few hundred thousand vectors this is fast enough to run inside a request; beyond that you reach for a vector database.

Memory is the other thing to watch. docs.nbytes tells you an array's size: 10,000 × 384 × 8 bytes is about 31 MB. Converting with docs.astype(np.float32) halves it, usually with no visible change in results. Load arrays like this once at startup, in the lifespan handler, not on every request.

Quick check
docs has shape (10000, 384) and query has shape (384,). What is the shape of docs @ query?
Need a nudge? A hint rules out a wrong answer.

Pitfalls worth knowing

  • Integer overflow. An int64 array wraps around silently past its limit, unlike Python's unlimited ints. Rarely a problem, but watch big products and sums of int32 data.
  • Float comparisons. Use np.isclose(a, b) or np.allclose, not ==, for computed floats.
  • Missing values. np.nan marks a missing float, and it poisons sums: np.sum returns nan. Use np.nansum, np.nanmean, or reach for pandas, which handles missing data properly.
  • JSON. FastAPI cannot serialise NumPy types directly. Call .tolist() on arrays and float(x) or int(x) on scalars before returning them.
Match the pairs0/5 matched

Match each task to the NumPy tool.

Choose an item, then its match on the other side.
Key terms
ndarray
NumPy's array: a fixed-size, contiguous block of values that all share one dtype.
dtype
The element type of an array, such as int64, float64 or bool.
vectorisation
Expressing work as whole-array operations so compiled code runs the loop instead of Python.
shape
A tuple of an array's size along each axis, like (3, 4) for 3 rows and 4 columns.
broadcasting
Rules that stretch size-1 dimensions so arrays of different shapes can be combined.
boolean mask
An array of True/False used as an index to select matching elements.
view
An array that shares memory with another. Slices are views; changes show up in both.