A subtle but crucial NumPy concept: many operations return a view that shares memory with the original array, while others return an independent copy. Knowing which prevents both aliasing bugs and wasted memory.
Slices are views
a = np.array([1, 2, 3, 4])s = a[1:3] # a VIEWs[0] = 99a # [ 1 99 3 4] — a changed too!
Making a copy
safe = a[1:3].copy() # independentsafe[0] = 0a # unchanged
Which is which?
| Returns a view | Returns a copy |
|---|---|
| Basic slicing (a[1:3]) | Fancy indexing (a[[0,2]]) |
| reshape (usually) | Boolean-mask indexing |
| .T (transpose) | .copy(), astype() |
Key takeaways
- 01A view shares memory with the original; writing to it changes the source.
- 02Basic slices, reshape and .T are views; fancy/boolean indexing and .copy()/.astype() are copies.
- 03Use .copy() when you need an independent array.
- 04arr.base reveals whether an array is a view (points at the source) or a copy (None).
