← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 2 of 7

Memory views

Views let two arrays share the same data so changes show up in both, with no copying.

In this page:

  1. Memory views
Syntax
python
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

python
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
  1. Modifying a view and forgetting the original changes
  2. Assuming fancy indexing returns a view
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.