Skip to content
BIASED

NumPy arrays

The array as a block of memory with a dtype, a shape and strides: views and copies, fixed-width integers and overflow, ufuncs and why they are fast, broadcasting, indexing, reductions, `@` and a seeded random generator.

One block of numbers

The topic Concurrency: threads, processes and asyncio spread work over threads and processes to use more of the machine. For numbers, a bigger gain comes first, before any parallelism: run the loop in compiled code instead of in the interpreter. The topic Writing fast Python previewed this with NumPy. This topic opens the Scientific Python module and explains what a NumPy array actually is, because one picture of it predicts most of its behaviour.

The examples use Python 3.14.7 and NumPy 2.5.4, run with uv run --python 3.14 --with numpy python. From the second session on, import numpy as np is assumed.

Take a thousand loss values, first in a list, then in an array:

>>> import sys
>>> import numpy as np
>>> losses = np.random.default_rng(0).random(1000).tolist()
>>> sys.getsizeof(losses), sys.getsizeof(losses[0])
(8056, 24)
>>> x = np.array(losses)
>>> x.dtype, x.itemsize, x.nbytes
(dtype('float64'), 8, 8000)
>>> type(losses[0]), type(x[0])
(<class 'float'>, <class 'numpy.float64'>)

The list is the dynamic array of references from the topic Lists and tuples: 8056 bytes of pointers and header. Each pointer leads to a separate float object of 24 bytes, so the whole list costs about 32 KB. The array holds the same numbers as 1000 raw 8-byte doubles, one after another: 8000 bytes. When you read one element, NumPy builds a fresh scalar object, numpy.float64, on the spot.

Key idea. A NumPy array (ndarray) is a pointer to one block of memory plus a description of that block:

  • a dtype: how to read one element (here float64, 8 bytes; float32 takes 4, int8 takes 1);
  • a shape: how many elements lie along each axis;
  • strides: how many bytes to step in memory to move one position along each axis.

The elements are raw machine values, not Python objects. So the size is plain arithmetic: nbytes is the number of elements times itemsize. And every operation does one of two things: it reads the same block through a new description, or it writes a new block.

Shape and strides

Strides are what make a flat block of bytes look like a matrix:

>>> a = np.arange(12).reshape(3, 4)
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> a.dtype, a.shape, a.strides
(dtype('int64'), (3, 4), (32, 8))
>>> f = np.asfortranarray(a)
>>> f.strides
(8, 24)
>>> a[2, 1], f[2, 1]
(np.int64(9), np.int64(9))

np.arange(12) makes twelve consecutive integers, 96 bytes. reshape(3, 4) describes the same bytes as three rows of four. The strides (32, 8) say that the next column is 8 bytes on and the next row is 32 bytes on, a whole row of four elements.

In general, an array with dd axes has shape (n0,…,nd−1)(n_0, \dots, n_{d-1}) and strides (s0,…,sd−1)(s_0, \dots, s_{d-1}) in bytes. The element with index (i0,…,id−1)(i_0, \dots, i_{d-1}) sits at this address:

address=start+∑k=0d−1ik sk.\text{address} = \text{start} + \sum_{k=0}^{d-1} i_k\, s_k .

A freshly created array comes in one of two orders. Let bb be the size of one element, itemsize.

  • C order (row-major, the default): the last index changes fastest. Then sd−1=bs_{d-1} = b and sk=sk+1 nk+1s_k = s_{k+1}\, n_{k+1}.
  • Fortran order (column-major, order="F"): the first index changes fastest. Then s0=bs_0 = b and sk=sk−1 nk−1s_k = s_{k-1}\, n_{k-1}.

np.asfortranarray copied the data into column order. The values are the same, the bytes are arranged differently, and the strides say how. The element a[2, 1] sits 2⋅32+1⋅8=722 \cdot 32 + 1 \cdot 8 = 72 bytes from the start of a, and 2⋅8+1⋅24=402 \cdot 8 + 1 \cdot 24 = 40 bytes from the start of f. It comes back as a NumPy scalar, np.int64(9); .item() turns it into a Python int.

Why the order matters. Memory is read in cache lines of 64 or 128 bytes. A walk along the axis with the small stride uses every byte of each line it loads. A walk along the large stride loads a new line for every element. NumPy picks a good order for its own operations, but the order matters when you hand data to other code: C and PyTorch expect row-major data, Fortran libraries such as LAPACK column-major. The course Computer Architecture and Operating Systems explains caches in depth.

Views and copies

An array is a description of memory, so many operations only write a new description.

The rule. These return a view, a new array object over the same block:

  • basic slicing with integers and start:stop:step (a[1], a[:, 1], a[::2, ::3]): the start moves, and each stride is multiplied by its step;
  • .T and transpose: the shape and the strides are reversed;
  • reshape and ravel, when the new shape can be described by strides over the same memory. Otherwise they copy.

These return a copy, a new block: indexing with a list or array of integers, indexing with a boolean mask, .copy(), flatten(), and arithmetic (a + 1 is a new array). np.shares_memory(x, y) tells whether two arrays overlap in memory.

>>> a = np.arange(12).reshape(3, 4)
>>> col = a[:, 1]
>>> col, col.strides, np.shares_memory(a, col)
(array([1, 5, 9]), (32,), True)
>>> a.T.strides, np.shares_memory(a, a.T)
((8, 32), True)
>>> np.shares_memory(a, a.reshape(4, 3)), np.shares_memory(a, a.T.reshape(12))
(True, False)
>>> np.shares_memory(a, a[[0, 2]]), np.shares_memory(a, a[a % 2 == 0])
(False, False)

The column a[:, 1] starts 8 bytes in and steps 32 bytes, one row, per element. The transpose just swaps the strides. a.reshape(4, 3) reads the same twelve numbers in the same order, so it is a view. a.T.reshape(12) wants the transpose in row order, 0, 4, 8, 1, …. No single stride walks the block in that order, so NumPy copies. An index list or a mask can pick any elements in any order, which no strides can describe.

The mistake. A view shares its data, so writing through it changes the original:

>>> a = np.arange(12).reshape(3, 4)
>>> row = a[1]
>>> row[0] = 100
>>> a
array([[  0,   1,   2,   3],
       [100,   5,   6,   7],
       [  8,   9,  10,  11]])
>>> np.reshape(a.T, 12, copy=False)
Traceback (most recent call last):
  ...
ValueError: Unable to avoid creating a copy while reshaping.

This is the aliasing from the topic Values, types and names, one level down: two array objects, one block. List slices copy; array slices do not. A function that receives a slice can change the caller's array, so take .copy() when it must not. A small view also keeps the whole block alive: big[:10] of a 1 GB array holds the gigabyte, while big[:10].copy() keeps ten elements. When code must not copy silently, np.reshape(x, shape, copy=False) (NumPy 2.1 and later) raises instead, as the last line shows.

Fixed-width numbers

The rule. All elements of an array share one dtype, a fixed-width machine type: int8 to int64, uint8 to uint64, float16, float32, float64, bool and a few more. Integer arithmetic wraps around modulo 2bits2^{\text{bits}}, with no error. Python's own int never overflows (topic Values, types and names); a NumPy integer does.

>>> x = np.array([100, 120, 127], dtype=np.int8)
>>> x + 1
array([ 101,  121, -128], dtype=int8)
>>> x * 2
array([-56, -16,  -2], dtype=int8)
>>> x + 200
Traceback (most recent call last):
  ...
OverflowError: Python integer 200 out of bounds for int8
>>> np.array([1, 2], dtype=np.uint8) - 3
array([254, 255], dtype=uint8)

int8 holds −128-128 to 127127. So 127+1127 + 1 wraps to 128−256=−128128 - 256 = -128, and 120⋅2=240120 \cdot 2 = 240 becomes 240−256=−16240 - 256 = -16. There is no warning: checking every element would cost as much as the arithmetic. The OverflowError comes from another rule of NumPy 2 (NEP 50). A Python number in an expression is "weak" and takes the array's dtype, so x + 1 stays int8, and a Python 200 that does not fit in int8 is refused outright. A NumPy scalar or array is "strong" and takes part in type promotion like any array.

Where it bites: images are stored as uint8, 0 to 255, and img1 - img2 wraps instead of going negative. Convert first: img.astype(np.int16), or img.astype(np.float32) / 255.

float32 against float64. float64 keeps about 16 significant decimal digits, float32 about 7. Half the bytes means half the memory traffic, which is why deep learning computes in float32 and narrower. The price shows in long sums:

>>> v = np.full(10_000_000, 0.1, dtype=np.float32)
>>> v.sum(), np.cumsum(v)[-1], v.sum(dtype=np.float64)
(np.float32(1.0000001e+06), np.float32(1.087937e+06), np.float64(1000000.0149011612))
>>> np.float32(16777216) + np.float32(1)
np.float32(1.6777216e+07)

Ten million copies of 0.1 should sum to 10610^6. v.sum() comes close because NumPy adds in pairs, a tree of additions whose rounding errors grow slowly. np.cumsum must add left to right. Near 10610^6 the gap between neighbouring float32 values is 1/161/16, each added 0.1 is rounded to a multiple of it, and the total ends up about 9% too high. At 224=16 777 2162^{24} = 16\,777\,216 the gap is 2, so adding 1 changes nothing. Accumulate long sums in float64.

Ufuncs and reductions

A universal function (ufunc) applies one scalar operation to every element: np.add (behind +), np.multiply (behind *), np.sqrt, np.exp, comparisons and about a hundred more.

The rule. A ufunc call does four things. It picks a compiled inner loop for the dtypes of its inputs, checks that their shapes fit together (the next block gives the rule), allocates the output and runs the inner loop over all elements.

Why it is fast. Three costs of the Python loop vanish together:

  1. Dispatch happens once per array, not once per element. The interpreter runs one call, and the type check is done once.
  2. The inner loop is typed C over raw values. There are no objects to create and no reference counts, and the fixed stride suits the cache.
  3. The inner loop uses SIMD instructions, which process several numbers in one instruction.

On one laptop (Apple M1, NumPy 2.5.4; your numbers will differ), the sum of squares of nn random floats took:

nn loop over a list loop over the array (x * x).sum() x @ x
10 0.30 µs 1.3 µs 0.71 µs 0.63 µs
1 000 000 24 ms 90 ms 0.55 ms 0.26 ms

A ufunc call has a fixed cost, here about 0.6 µs, so for ten numbers the plain list loop wins. A Python loop over an array is the worst of all, because each for v in x builds a NumPy scalar object. And every intermediate result is a full temporary array: (x * x).sum() writes all of x * x to memory and reads it back, while x @ x computes the same number in one pass. Vectorize work on large arrays, and never walk an array element by element in Python.

A ufunc also has methods built on the same loop. reduce folds an axis into one value, and np.sum is np.add.reduce. Such a reduction (sum, mean, std, min, max, argmax, any, all) runs over all elements or along one axis:

>>> x = np.array([1.0, 2.0, 3.0])
>>> np.multiply(x, x), x * x
(array([1., 4., 9.]), array([1., 4., 9.]))
>>> np.add.reduce(x), np.add.accumulate(x)
(np.float64(6.0), array([1., 3., 6.]))
>>> a = np.arange(12).reshape(3, 4)
>>> a.sum(), a.sum(axis=0), a.sum(axis=1)
(np.int64(66), array([12, 15, 18, 21]), array([ 6, 22, 38]))
>>> a.sum(axis=1, keepdims=True).shape
(3, 1)

The rule for axis. With axis=k, the reduction runs along axis kk, and that axis disappears from the shape. A (3,4)(3, 4) array with axis=0 gives shape (4,)(4,), one result per column; with axis=1, shape (3,)(3,), one per row. keepdims=True keeps the reduced axis with size 1. In the ML courses a data matrix XX has one row per object, so X.mean(axis=0) is the vector of feature means.

Broadcasting

Arithmetic between different shapes is everyday work: subtract each column's mean from a matrix, add a bias vector to every row of a batch. NumPy defines it with one rule instead of asking you to copy arrays to equal shapes.

The rule. To combine two arrays:

  1. Line up their shapes on the right. Pad the shorter shape on the left with 1s.
  2. Compare the sizes axis by axis. Two sizes fit when they are equal or one of them is 1. Any other pair raises ValueError.
  3. The result takes the larger of the two sizes on each axis.
  4. An operand of size 1 on an axis is used as if repeated along it. Nothing is copied: the repeated axis gets stride 0.

Worked: a column of shape (3, 1) plus a row of shape (4,). Padded, the row is (1, 4). The pairs are 3 with 1 and 1 with 4; both fit, so the result has shape (3, 4). Its entry (i,j)(i, j) is coli+rowj\text{col}_i + \text{row}_j:

>>> col = np.array([[0], [10], [20]])
>>> row = np.array([1, 2, 3, 4])
>>> col + row
array([[ 1,  2,  3,  4],
       [11, 12, 13, 14],
       [21, 22, 23, 24]])
>>> np.broadcast_to(row, (3, 4)).strides
(0, 8)
>>> np.ones(3) + np.ones(4)
Traceback (most recent call last):
  ...
ValueError: operands could not be broadcast together with shapes (3,) (4,)

The stride 0 is the "repeat" of step 4: the stretched row reads the same four numbers for every row.

Centering a data matrix XX of shape (n,d)(n, d) is the everyday use. X.mean(axis=0) has shape (d,)(d,), which lines up with the last axis of XX, so X - X.mean(axis=0) subtracts each column's mean from that column. Centering the rows needs the row means as a column, which keepdims=True gives:

>>> X = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 18.]])
>>> X - X.mean(axis=1, keepdims=True)
array([[-1.,  0.,  1.],
       [-1.,  0.,  1.],
       [-4., -3.,  7.]])
>>> X - X.mean(axis=1)
array([[-1., -3., -8.],
       [ 2.,  0., -5.],
       [ 5.,  3.,  7.]])

The mistake. Broadcasting never asks what you meant. The last line forgot keepdims. The row means [2, 5, 11] have shape (3,), line up with the columns, and get subtracted from the three columns. For a square XX this runs without a word. The classic case is a loss:

>>> y = np.array([1., 2., 3.])
>>> pred = np.array([[1.], [2.], [3.]])
>>> (y - pred).shape, ((y - pred) ** 2).mean()
((3, 3), np.float64(1.3333333333333333))
>>> ((y - pred[:, 0]) ** 2).mean()
np.float64(0.0)

The model returns predictions of shape (n,1)(n, 1), the targets have shape (n,)(n,), and y - pred is an n×nn \times n table of every target minus every prediction. The predictions are perfect, yet the "mean squared error" is 1.33. Check shapes with assert pred.shape == y.shape, or flatten with pred[:, 0]. PyTorch uses the same rules and has the same trap.

Indexing: basic, fancy and boolean

Three kinds of index select elements, and the kind decides whether you get a view:

  • Basic: integers, slices, None (a new axis of size 1) and .... It returns a view, as in block 3.
  • Fancy (lists or arrays of integers): a[[2, 0]] takes rows 2 and 0 in that order; a[[0, 1, 2], [3, 2, 1]] takes the elements (0,3)(0, 3), (1,2)(1, 2) and (2,1)(2, 1). It returns a copy.
  • Boolean (a mask of the same shape): a[a > 8] returns the elements where the mask is true, as a 1-D copy.
>>> a = np.arange(12).reshape(3, 4)
>>> a[[2, 0]]
array([[ 8,  9, 10, 11],
       [ 0,  1,  2,  3]])
>>> a[[0, 1, 2], [3, 2, 1]]
array([3, 6, 9])
>>> a[a > 8]
array([ 9, 10, 11])
>>> a[a > 8] = 0
>>> a
array([[0, 1, 2, 3],
       [4, 5, 6, 7],
       [8, 0, 0, 0]])
>>> a[a > 6][0] = 99
>>> a
array([[0, 1, 2, 3],
       [4, 5, 6, 7],
       [8, 0, 0, 0]])

Reading through a fancy or boolean index copies. Assigning through one writes into the original: a[a > 8] = 0 is a single call, a.__setitem__(mask, 0), and it writes in place (the special methods from the topic The data model). The trap is to chain the two. a[a > 6][0] = 99 first calls __getitem__, which makes a copy, and then changes the copy; a is untouched. The same chained-indexing trap returns in pandas.

Fancy indexing is also how ML code looks rows up. Given a table of per-category values and an array of category numbers, table[categories] fetches one row per object in a single call.

The matrix product and random numbers

* is elementwise. The matrix product is the operator @, which calls np.matmul.

The rule. For 2-D arrays of shapes (n,k)(n, k) and (k,m)(k, m), A @ B has shape (n,m)(n, m). The inner sizes must match, and each entry is a sum over the shared index:

(AB)ij=∑lAil Blj.(AB)_{ij} = \sum_{l} A_{il}\, B_{lj} .

A 1-D first operand acts as a row and a 1-D second operand as a column; the added axis is then dropped. So A @ x of shapes (n,k)(n, k) and (k,)(k,) is a vector of shape (n,)(n,), and x @ x is a number. With more than two axes, the last two are the matrices and the leading ones form a batch, broadcast by the rule of block 6.

>>> A = np.array([[1, 2], [3, 4]])
>>> x = np.array([1, 10])
>>> A @ x
array([21, 43])
>>> A * x
array([[ 1, 20],
       [ 3, 40]])
>>> (np.ones((5, 3, 4)) @ np.ones((4, 2))).shape
(5, 3, 2)
>>> np.ones((2, 3)) @ np.ones((2, 3))
Traceback (most recent call last):
  ...
ValueError: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 2 is different from 3)

A @ x is (1+20, 3+40)(1 + 20,\ 3 + 40), the matrix applied to the vector. A * x stretches x along the rows and multiplies elementwise: a different operation that also runs without error. The batched product multiplies each of five 3×43 \times 4 matrices by the same 4×24 \times 2 one. The error message spells the rule out in its signature: the k of the first operand must equal the k of the second. What the product means, a linear map and the system Ax=bAx = b, is the subject of the course Mathematics for ML (topic Matrices and linear systems).

Random numbers. Create one generator with a seed and draw everything from it:

>>> rng = np.random.default_rng(42)
>>> rng.random(3)
array([0.77395605, 0.43887844, 0.85859792])
>>> rng.integers(0, 10, size=5)
array([0, 6, 2, 0, 5])
>>> np.random.default_rng(42).random(3)
array([0.77395605, 0.43887844, 0.85859792])

rng.random(3) draws three uniform numbers in [0,1)[0, 1), and rng.integers(0, 10, size=5) five integers from 0 to 9; rng.normal, rng.permutation and rng.choice cover the rest. This is not a generator in the sense of the topic Iteration, comprehensions and generators but an object with internal state, so each call continues the stream. A new generator with the same seed starts the stream again. The old style, np.random.seed(0) and then np.random.rand(...), keeps one hidden global state that any library you call can advance; new code passes a generator explicitly. The same seed gives the same numbers on the same NumPy version, so record the version next to your results.

An array holds numbers of one dtype, found by position. Real data come as tables: a column of run names next to a column of losses and a column of dates, rows found by a key rather than a position, values that are missing. The next topic, Data frames with pandas, builds such a table as labeled columns over arrays like these.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Broadcasting and matmuloptional

    Check broadcast (3,1)+(1,4) and @ shapes; catch a misaligned case.

    ~20 min · easier on a computer · The matching course topic has been read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.