Sub topic 15
Memory layout and strides
This chapter assumes you know shape, dtype, and the difference between views and copies from earlier chapters. It explains how NumPy finds each element in memory. That explains why a transpose costs nothing and why a reshape sometimes copies.
One flat buffer, many shapes
An ndarray stores its elements in one flat block of memory. The shape is only a rule for reading that block. The rule is stored as strides, a tuple with one entry per axis. Each entry is the number of bytes to skip to move one step along that axis.
import numpy as np
a = np.arange(6, dtype=np.int64).reshape(2, 3)
print(a.strides) # (24, 8): bytes to step along each axis
print(a.T.strides) # (8, 24): transpose swaps strides, no data copied
print(a.T.flags['C_CONTIGUOUS']) # FalseEach int64 takes 8 bytes. Moving one column along a row skips 8 bytes. Moving one row skips 3 elements, which is 24 bytes. The transpose reuses the same buffer and swaps the two strides.
C order and Fortran order
NumPy defaults to C order (row-major), where the last axis changes fastest in memory. Fortran order (column-major) makes the first axis change fastest. Strides show which one an array uses.
import numpy as np
a = np.arange(6, dtype=np.int64).reshape(2, 3)
f = np.asfortranarray(a)
print(f.strides) # (8, 16)
print(f.flags['F_CONTIGUOUS']) # True
print(a[:, ::2].strides) # (24, 16): a step slice doubles one stride
print(np.shares_memory(a, a.T)) # True: the transpose is a viewSlicing with a step also gives a view. NumPy only changes the strides and the starting offset.
When reshape copies
reshape returns a view when the requested shape can be described with strides over the existing buffer. Otherwise it makes a copy. A transposed array usually cannot be flattened this way, because its elements are not in reading order in memory.
import numpy as np
a = np.arange(6, dtype=np.int64).reshape(2, 3)
flat_view = a.reshape(6)
flat_copy = a.T.reshape(6)
print(np.shares_memory(a, flat_view)) # True
print(np.shares_memory(a, flat_copy)) # False: a.T is not contiguousRelated methods behave differently:
| Method | Result |
|---|---|
| `ravel()` | A view if possible, otherwise a copy |
| `flatten()` | Always a copy |
| `np.ascontiguousarray(x)` | A C-contiguous array, copied only if needed |
Why layout affects speed
Reading memory in order is faster, because the CPU loads nearby bytes together. Summing along the contiguous axis walks the buffer in order. Summing along a large stride jumps through memory. The difference grows with array size. When a hot loop runs over a non-contiguous array, np.ascontiguousarray pays a one-time copy to speed up later passes.
Exercise
An array is created with np.zeros((4, 5), dtype=np.float32). What are the strides of a and of a.T?
Show answer
a.strides is (20, 4). A float32 takes 4 bytes, and a row has 5 elements, so one row step is 20 bytes. a.T.strides is (4, 20), because the transpose swaps the strides without copying data.