Memory views
Views let two arrays share the same data so changes show up in both, with no copying.
In this page:
Syntax
view = arr[start:stop] # shares memory
copy = arr[start:stop].copy() # independent
Memory views
Slicing, reshape and transpose normally return views that share memory with the original. A copy, made with .copy(), owns its own data. The .base attribute tells you whether an array is a view, and np.shares_memory checks overlap.
Note:
Views save memory and time, but a change through one shows up in all.
Example: Memory views
import numpy as np
a = np.arange(6)
v = a[1:4]
c = a[1:4].copy()
v[0] = 99
print(a)
print("view shares:", np.shares_memory(a, v))
print("copy shares:", np.shares_memory(a, c))
print(v.base is a)
# Output:
# [ 0 99 2 3 4 5]
# view shares: True
# copy shares: False
# True
Related Topics
Common Mistakes
- Modifying a view and forgetting the original changes
- Assuming fancy indexing returns a view
- Not copying before destructive edits
Chapter Summary
- Slices and reshapes are views
- copy() makes independent data
- base reveals the owner
- shares_memory checks overlap
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: