Sub topic 15
Memory layout and strides
This chapter assumes you know shape, dtype, views versus copies, and reshaping from earlier chapters. Here you will see how an array's metadata maps indices onto one flat block of memory. That mapping explains why transposes are free, why some reshapes copy, and why loop order can change speed.
One flat buffer plus metadata
An ndarray is a single contiguous block of bytes plus a small header. The header records:
- the dtype, which gives the size of one element (
itemsize) - the shape
- the strides, which are the number of bytes to step to reach the next element along each axis
- an offset to the first element, and a reference to the memory owner
The address of element a[i, j] is:
start + i * strides[0] + j * strides[1]
Because the formula is the same for every axis, NumPy never needs nested storage like a list of lists. Changing the strides changes how the same bytes are read.
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']) # FalseThe array holds 8-byte integers with three columns. Moving one column costs 8 bytes. Moving one row costs 3 × 8 = 24 bytes. The transpose reuses the same buffer and swaps the two numbers.
C order and Fortran order
Memory order decides which axis has the smallest stride.
| Order | Name | Fastest-changing axis | Strides of a (2, 3) int64 array |
|---|---|---|---|
| `'C'` | row-major (default) | last axis | (24, 8) |
| `'F'` | column-major | first axis | (8, 16) |
In C order the elements of a row sit next to each other. In Fortran order the elements of a column do. You can choose the order when you create or copy an array.
import numpy as np
c = np.arange(6, dtype=np.int64).reshape(2, 3)
f = np.asfortranarray(c)
print(c.strides, f.strides) # (24, 8) (8, 16)
print(c.flags['C_CONTIGUOUS'], c.flags['F_CONTIGUOUS']) # True False
print(f.flags['C_CONTIGUOUS'], f.flags['F_CONTIGUOUS']) # False True
print(np.array_equal(c, f)) # True: same values, different layoutBoth arrays hold the same values. Only the byte layout differs. A one-dimensional contiguous array is both C and F contiguous. A transposed C array is F contiguous, so c.T has the same layout as a Fortran-order copy of c.T.
Slicing is stride arithmetic
A basic slice does not move data. It adjusts the start offset, the shape, and the strides.
import numpy as np
a = np.arange(12, dtype=np.int64).reshape(3, 4)
print(a.strides) # (32, 8)
print(a[:, ::2].strides) # (32, 16): every second column, so double the column step
print(a[::-1].strides) # (-32, 8): a negative stride walks backwards
print(a[:, 1].strides) # (32,): one column, a 1-D view down a column
print(a[:, 1].base is a) # True: the slice refers to a's memoryThis is why basic slices are views, as the views-versus-copies chapter showed. It also means a view can be non-contiguous. a[:, ::2] skips bytes, so it is neither C nor F contiguous.
Why reshape sometimes copies
reshape returns a view when the new shape can be described with strides over the existing buffer. Otherwise it copies. A C-contiguous array can always be reshaped as a view. A transposed one usually cannot.
import numpy as np
a = np.arange(6, dtype=np.int64).reshape(2, 3)
flat = a.reshape(6)
print(np.shares_memory(a, flat)) # True: a view
t_flat = a.T.reshape(6)
print(np.shares_memory(a, t_flat)) # False: NumPy had to copy
print(t_flat) # [0 3 1 4 2 5]a.T is [[0, 3], [1, 4], [2, 5]]. Reading it in C order gives 0, 3, 1, 4, 2, 5. Those values are not in one regular stride pattern in the original buffer, so NumPy builds a new contiguous array.
The related methods differ in the same way. ravel() returns a view when it can and a copy otherwise. flatten() always copies. Assigning to a.shape never copies, and it raises an error if a copy would be needed.
Zero strides and broadcasting
Broadcasting also uses strides. A broadcast axis gets a stride of 0, so every index along it reads the same element.
import numpy as np
row = np.array([1, 2, 3], dtype=np.int64)
b = np.broadcast_to(row, (4, 3))
print(b.shape) # (4, 3)
print(b.strides) # (0, 8): the row axis does not advance in memory
print(b.flags['WRITEABLE']) # FalseThe 4 × 3 array costs no extra data. NumPy marks it read-only, because writing to one element would appear to change four of them.
Building views with strides
sliding_window_view shows the idea directly. It builds overlapping windows by giving two axes the same stride.
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
x = np.arange(6, dtype=np.int64)
w = sliding_window_view(x, 3)
print(w)
# [[0 1 2]
# [1 2 3]
# [2 3 4]
# [3 4 5]]
print(w.shape, w.strides) # (4, 3) (8, 8)
print(w.mean(axis=1)) # [1. 2. 3. 4.]
print(np.shares_memory(x, w)) # TrueBoth axes step by 8 bytes, so each row starts one element after the previous row. The result is a read-only view. The lower-level np.lib.stride_tricks.as_strided can build the same thing without safety checks. A wrong shape or stride there reads memory outside the array, so prefer sliding_window_view.
Layout and speed
Modern CPUs load memory in cache lines, typically 64 bytes. When a loop reads consecutive addresses, one load serves several elements. When it jumps by a large stride, each element can cost a separate cache line.
For a C-ordered array, summing along the last axis reads memory in order, while summing along axis 0 moves down columns. The gap is most visible on large arrays that exceed the CPU cache.
import numpy as np
from timeit import timeit
n = 4000
c = np.ones((n, n), dtype=np.float64) # C order
f = np.asfortranarray(c) # same values, F order
for name, arr in [("C", c), ("F", f)]:
t0 = timeit(lambda: arr.sum(axis=0), number=5)
t1 = timeit(lambda: arr.sum(axis=1), number=5)
print(f"{name} order: axis=0 {t0:.3f}s, axis=1 {t1:.3f}s")The timings depend on your hardware, so no fixed output is shown. Expect the preferred axis to differ between the two layouts. Also, NumPy's reduction code can reorder loops internally, so the gap is often smaller than a pure stride argument predicts. Measure on your own data before restructuring code.
Practical rules
- Check
arr.flagsandarr.strideswhen a result is surprising. - Use
np.ascontiguousarray(a)before passing data to C or Fortran libraries that need a specific layout. It copies only when the input is not already contiguous. - A transpose followed by a heavy operation can be slow. Making one contiguous copy with
.copy()can pay for itself if you then process the array many times. - Use
np.shares_memorywhen you must know whether two arrays alias each other. Thebaseattribute shows only the immediate owner. - Do not assume the stride values in this chapter on every system. They scale with the dtype's
itemsize.
Exercise
Let a = np.arange(12, dtype=np.int32).reshape(3, 4). What are a.strides and a[:, ::2].strides? Is a[:, ::2] C contiguous?
Show answer
An int32 element is 4 bytes, and each row has 4 elements, so a.strides is (16, 4). Taking every second column doubles the column step: a[:, ::2].strides is (16, 8). The slice skips elements, so it is not C contiguous.
Exercise
Why does a.T.reshape(-1) copy while a.reshape(-1) does not, for a C-contiguous 2-D array a? How can you confirm it?
Show answer
a.reshape(-1) reads the buffer in its stored order, which one stride can describe, so NumPy returns a view. a.T reads the same bytes in a different order. The flattened order of a.T cannot be written as one stride over the original buffer, so NumPy allocates a new array. Confirm with np.shares_memory(a, a.reshape(-1)), which is True, and np.shares_memory(a, a.T.reshape(-1)), which is False.