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;float32takes 4,int8takes 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.