Being Naughty with Numpy

Fun
Tee-hee
Author

Bailey Andrew

Published

January 29, 2023

# Setup
import numpy as np

X = np.arange(12).reshape(3, 4)
A = X[:2]
B = X[2:]
display(A)
display(B)
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
array([[ 8,  9, 10, 11]])
# Depends only on A
np.lib.stride_tricks.as_strided(
    A,
    shape=(12,),
    strides=(A.itemsize,)
)[-1] = -1

# A hasn't changed
display(A)
array([[0, 1, 2, 3],
       [4, 5, 6, 7]])
# Spooky!
display(B)
array([[ 8,  9, 10, -1]])

Can you figure out why?

Hint: How does the NumPy memory model work?