An ndarray is a view over a buffer described by shape, dtype, and strides (byte steps per axis). Reshape and slice often reuse memory without copying.
View vs copy
import numpy as np
a = np.arange(6)
b = a.reshape(2, 3)
print(np.may_share_memory(a, b))
Explicit copy
arr.copy() allocates new buffer—use before mutating when unsure if array is a view.
ascontiguousarray
C libraries and some BLAS calls expect C-contiguous layout. np.ascontiguousarray copies only when needed.
Important interview questions and answers
- Q: may_share_memory?
A: Heuristic check whether two arrays might alias same data. - Q: Why contiguous matters?
A: Some optimized kernels skip non-contiguous inputs or copy silently.
Self-check
- When should you call .copy()?
- What attribute describes byte steps per dimension?
Pitfall: Call .copy() before in-place ops on uncertain views.
Interview prep
- copy when?
Before mutating if array might be a view of shared data.
- strides?
Byte step per axis—defines layout without copying.