Sub topic 6
Views versus copies
This chapter assumes you can create arrays, read shape and dtype, and use basic indexing and slicing. It covers when NumPy shares memory between arrays and when it duplicates data. Mixing these up is a common source of bugs.
What a view is
A view is a new array object that reads the same block of memory as another array. The two objects have their own shape and strides, but they share the data. Writing through one changes what the other shows. A copy owns separate memory, so changes to it never affect the original.
Basic slicing returns a view. This is what makes slicing fast, because no data moves.
import numpy as np
a = np.arange(6)
s = a[1:4] # basic slice: a view
s[0] = 99
print(a) # [ 0 99 2 3 4 5]
c = a[1:4].copy() # independent copy
c[0] = -1
print(a) # unchanged: [ 0 99 2 3 4 5]Changing s[0] changed a[1]. The explicit .copy() broke the link, so c can change freely.
Which operations give which
The rule is tied to the kind of indexing, not to how the code looks.
| Operation | Result |
|---|---|
| `a[1:4]`, `a[:, 0]` (basic slicing) | View |
| `a.T`, `a.reshape(...)` when possible | View |
| `a[a > 0]` (boolean mask) | Copy |
| `a[[0, 2]]` (integer list) | Copy |
| `a + 1`, `np.sqrt(a)` (arithmetic and ufuncs) | New array |
| `a.copy()` | Copy |
reshape returns a view when the existing memory layout allows it. Otherwise it quietly returns a copy. Do not rely on either outcome unless you check.
Checking for shared memory
Two tools tell you what happened. The base attribute is None for an array that owns its data. For a view, it points to the array that owns the data. The function np.shares_memory compares two arrays directly.
import numpy as np
a = np.arange(6)
v = a[1:4]
m = a[[1, 2, 3]]
print(v.base is a) # True
print(m.base is None) # True
print(np.shares_memory(a, v)) # True
print(np.shares_memory(a, m)) # FalseAssignment through fancy indexing
A copy can also trip you up when you chain indexing. The first index may return a copy, so the write lands on a temporary array and is lost.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
a[a < 0] = 0 # one indexing step: modifies a
print(a) # [3 0 4 0 9]
b = np.array([3, -1, 4, -5, 9])
b[b < 0][0] = 100 # b[b < 0] is a copy, so this write is lost
print(b) # [ 3 -1 4 -5 9]Assignment with a single a[mask] = value is translated into one __setitem__ call on a, so it works. In the chained form, the mask step produces a temporary copy, and that copy is what you assign into.
Common errors
- Mutating a slice by accident. Passing
a[1:4]to a function that edits its argument also editsa. Call.copy()if the function should not touch the original. - Holding a large array alive. A small view keeps its whole base array in memory. Copy the slice you need, then delete the large array.
- Assuming
b = acopies. Plain assignment binds a second name to the same array object. Neither a view nor a copy is created.
Exercise
Given a = np.arange(5), you run b = a[::2] and then b[:] = 0. What does a contain, and what would change if you had written b = a[[0, 2, 4]] instead?
Show answer
With the slice a[::2], b is a view, so a becomes [0 1 0 3 0]. Writing the zeros changed elements 0, 2, and 4 of a. With the integer list a[[0, 2, 4]], b is a copy, so a stays [0 1 2 3 4].