0
0
NumPydata~5 mins

Strides and how data is accessed in NumPy

Choose your learning style9 modes available
Introduction

Strides tell us how many bytes we need to jump to get to the next element in each dimension of an array. This helps us understand how data is stored and accessed in memory.

When you want to understand how numpy stores multi-dimensional arrays in memory.
When you need to optimize code by knowing how data is accessed for faster processing.
When you want to create views or slices of arrays without copying data.
When debugging unexpected behavior related to array shapes or memory layout.
Syntax
NumPy
array.strides

strides is a tuple showing the number of bytes to step in each dimension when moving to the next element.

It depends on the data type size and the shape of the array.

Examples
This prints the strides of a 2x3 integer array.
NumPy
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.strides)
Shows strides for a 1D array with 16-bit integers (2 bytes each).
NumPy
arr = np.array([1, 2, 3, 4], dtype=np.int16)
print(arr.strides)
Compare strides of an array and its transpose to see how data access changes.
NumPy
arr = np.arange(6).reshape(2, 3)
arr_T = arr.T
print(arr.strides)
print(arr_T.strides)
Sample Program

This program shows how strides tell us the byte steps to move in each dimension. It also shows how slicing creates a view sharing the same data, so changes in the view affect the original array.

NumPy
import numpy as np

# Create a 2D array
arr = np.array([[10, 20, 30], [40, 50, 60]], dtype=np.int32)

# Print the array
print("Array:")
print(arr)

# Show the strides
print("Strides:", arr.strides)

# Access elements using strides info
# Each int32 is 4 bytes, so strides tell how many bytes to jump

# Create a view by slicing columns
view = arr[:, 1:]
print("View:")
print(view)
print("View strides:", view.strides)

# Modify view and see effect on original
view[0, 0] = 999
print("Modified original array:")
print(arr)
OutputSuccess
Important Notes

Strides are in bytes, not in number of elements.

Changing the shape or transposing an array changes strides, affecting how data is accessed.

Views share data with the original array, so modifying a view changes the original.

Summary

Strides tell how many bytes to jump to move to the next element in each dimension.

They help understand memory layout and data access patterns.

Slicing creates views with their own strides but shared data.