A NumPy array stores typed values in a buffer, while an array view can refer to selected positions in another array’s buffer.
NumPy slices and indexed copies: verify who owns the buffer
Operation contract
The receipt amounts use an explicit signed 64-bit integer dtype. A basic slice shares the original buffer, so changing its first value changes the original amount. Selecting positions with an integer index list makes a separate array in this fixture. shares_memory checks those relationships instead of assuming every array-returning operation copies.
Failure and ownership boundary
These are small one-dimensional numeric arrays. Object arrays can retain Python object references, and reshaping or layout changes need their own view/copy checks. A buffer alias can expose caller-owned data to later mutation. Python shallow and deep copies: preserve aliases deliberately uses a different representation, while NumPy broadcasting: declare axes and bound integer arithmetic adds shape rules.
Tested environment
Dependency check: this program was executed on CPython 3.14.6 with numpy==2.5.3. Install these versions in a separate virtual environment. The download includes the recorded environment snapshot; no third-party package is part of the website runtime.
Working program
import numpy as np
amounts = np.array([125, 75, 90], dtype=np.int64)
view = amounts[1:]
selected = amounts[[1, 2]]
view[0] = 80
selected[0] = 999
print(amounts.tolist())
print(selected.tolist())
print(bool(np.shares_memory(amounts, view)))
print(bool(np.shares_memory(amounts, selected)))Output
[125, 80, 90]
[999, 90]
True
FalseCosts and limits
The slice creates view metadata without copying its numeric buffer. Advanced selection allocates O(k) selected elements here. shares_memory itself can be expensive for complicated strided layouts; this fixture has simple contiguous storage.
Common Mistakes
- Do not mutate a borrowed slice while promising to preserve the caller’s data.
- NumPy copy/view behavior is not the same as copying a list’s object references.
Connected lessons
Python lists: slicing copies the outer sequence, not nested objects, Python shallow and deep copies: preserve aliases deliberately, NumPy broadcasting: declare axes and bound integer arithmetic.
