Sub topic 5
Views versus Copies: When Slicing Shares Memory
This chapter assumes you can create arrays with np.array, np.arange, and reshape, and that you know what shape and dtype mean. It also assumes you have used integer indices and start:stop:step slices on arrays. The question here is whether a selection gives you the same data or new data. That decides whether a later write changes the original array.
Two kinds of result
An indexing operation returns one of two things.
- A view is a new array object that reads and writes the same memory buffer as the original. No elements are duplicated. Writing through the view changes the original, and the reverse also holds.
- A copy has its own buffer. The two arrays are independent after creation.
A NumPy array is a small header (shape, strides, dtype, and a pointer) over a block of memory. A basic slice makes a new header that points into the same block with different bounds and strides. Copying the data would cost time and memory proportional to the number of elements. A view costs almost nothing, whatever the slice size.
The rule for indexing
| Operation | Result | Why |
|---|---|---|
| `a[1:3]`, `a[:, ::2]`, `a[::-1]` | view | Any regular pattern of start, stop, and step can be described by shape and strides |
| `a[1]` on a 2-D array (a row) | view | It is a slice with one axis dropped |
| `a[..., 0]`, `a[:, np.newaxis]` | view | These change only the header |
| `a[1, 2]` | scalar | A single value is returned, not an array |
| `a[[0, 2]]` (integer list or array) | copy | Arbitrary positions do not fit a strided pattern |
| `a[a > 0]` (boolean mask) | copy | The selected positions are arbitrary, and the result is packed into a new 1-D array |
| `a.T`, `a.reshape(...)` | view when possible | Strides can be rearranged without moving data |
| `a.ravel()` | view if contiguous, else copy | A flat view needs one regular stride |
| `a.flatten()`, `a.copy()` | always a copy | These are documented to copy |
The deciding factor is whether the selected elements can be described by a start offset, a shape, and one stride per axis. Slices can be described that way, so they return views. An arbitrary list of positions cannot, so it returns a copy.
Seeing it happen
This example runs the whole sequence: a slice shares memory, .copy() does not, and fancy indexing does not.
import numpy as np
a = np.arange(12).reshape(3, 4)
view = a[:, :2]
view[0, 0] = 99
print(a[0, 0]) # 99, because a slice is a view of a
independent = a[:, :2].copy()
independent[0, 0] = -1
print(a[0, 0]) # still 99
rows = a[[0, 1]] # fancy indexing returns a copy
rows[0, 0] = -5
print(a[0, 0]) # still 99
print(np.shares_memory(a, a[:, :2])) # TrueThe first write goes through view and shows up in a. The next two writes go to independent buffers, so a does not change.
The effect also works in the other direction. If you assign to a[0, 0] after creating view, then view[0, 0] shows the new value.
Checking instead of guessing
Three tools tell you whether memory is shared.
np.shares_memory(x, y)returnsTrueif the two arrays overlap in memory. It gives an exact answer, but it can be slow for complicated overlaps.np.may_share_memory(x, y)only compares the memory bounds. It is fast and can give false positives, but not false negatives.x.baseis the array that owns the buffer, orNoneifxowns its own data.x.flags.owndatareports the same thing as a boolean.
import numpy as np
a = np.arange(6)
v = a[1:4]
c = a[[1, 2, 3]]
print(v.base is a) # True
print(c.base is None) # True
print(a.flags.owndata) # True
print(v.flags.owndata) # False
print(np.shares_memory(a, v)) # True
print(np.shares_memory(a, c)) # False.base has a catch. An array produced by reshape is itself a view, so np.arange(12).reshape(3, 4).base is the original arange array, not None. Use np.shares_memory to answer "do these two arrays overlap?". It is more reliable than comparing .base attributes, because a view of a view points to the root owner, and two views of the same buffer can differ in how they were made.
Reshaping, transposing, and flattening
Several common methods also return views, and their rules differ.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(np.shares_memory(a, a.T)) # True
print(np.shares_memory(a, a.ravel())) # True, a is contiguous
print(np.shares_memory(a, a[:, ::2].ravel())) # False, columns are not contiguous
print(np.shares_memory(a, a.flatten())) # False, flatten always copies.Tswaps the strides and never copies..reshapereturns a view when the new shape is compatible with the existing memory layout. Otherwise it quietly returns a copy. Do not depend on either outcome unless you have checked..ravel()returns a view only when the elements are already laid out in the flat order you want.a[:, ::2]skips elements, so flattening it needs a copy.
If your code must not modify the original, call .copy() explicitly. If it must modify the original, assign into the array directly with a[...] = value and do not rely on a reshape returning a view.
Assignment always writes in place
An indexing expression on the left of = does not create a new array. It writes into the original, whatever kind of index you use. That is why fancy indices and masks work for modifying values even though they return copies when read.
import numpy as np
a = np.arange(6)
a[[0, 2]] = -1 # writes into a
print(a) # [-1 1 -1 3 4 5]
a[a > 3] = 0 # writes into a
print(a) # [-1 1 -1 3 0 0]Reading with a fancy index copies. Writing with the same index modifies the array you wrote to.
The chained-assignment trap
The behavior above becomes a bug when you chain two indexing operations. Python evaluates a[x][y] = v as tmp = a[x] followed by tmp[y] = v. Whether the write reaches a depends on whether a[x] returned a view or a copy.
import numpy as np
a = np.arange(6)
a[a > 2][0] = 100 # a[a > 2] is a copy, so the write is lost
print(a) # [0 1 2 3 4 5]
a[3:][0] = 100 # a[3:] is a view, so the write reaches a
print(a) # [ 0 1 2 100 4 5]The first line raises no error and gives no warning. The result is silently wrong. The fix is to combine the selection into one indexing operation on the left, such as a[3] = 100, or to compute the integer position first and assign to it.
Views and function arguments
A slice passed to a function still points at the caller's data. Any in-place change inside the function is visible outside.
import numpy as np
def zero_first(x):
x[0] = 0
grid = np.arange(1, 7).reshape(2, 3)
zero_first(grid[1]) # row 1 is a view
print(grid)
# [[1 2 3]
# [0 5 6]]
zero_first(grid[[0]][0]) # grid[[0]] is a copy
print(grid[0, 0]) # still 1Document functions that modify their inputs. When a function needs a scratch array, copy at its start with x = np.array(x) or x = x.copy().
Memory kept alive by a view
A view holds a reference to its base. As long as a tiny slice exists, the whole original buffer stays in memory.
import numpy as np
big = np.arange(1_000_000)
small = big[:3] # keeps the whole buffer alive
small_own = big[:3].copy() # owns only 3 elements
print(small.base is big) # True
print(small_own.base is None) # True
print(small.nbytes, small_own.nbytes) # 24 24 with 64-bit integersnbytes counts only the elements in the array, so both report 24 bytes. The difference appears when you delete big. small still holds the full buffer, which is about 8 MB with 64-bit integers. small_own holds only 24 bytes. If you keep a small result for a long time, for example in a cache, copy it so the large array can be freed.
A decision procedure
The diagram summarizes how to predict the result of an index expression.
The first test decides everything. If the expression contains any array-valued index, including one mixed with slices such as a[:, [0, 2]], the read returns a copy.
Summary of habits
- Treat every slice as a window onto the original. Call
.copy()when you want to keep the result separate. - Do not rely on the result of
reshapeorravelbeing a view or a copy. Check withnp.shares_memorywhen it matters. - Do not chain indexing on the left side of an assignment. Use one index expression.
- Copy small results taken from large arrays if they will live a long time.
Exercise
Given a = np.arange(10), you run b = a[2:6], then b[:] = 0, then c = a[[6, 7]], then c[:] = 9. What does a contain at the end, and why?
Show answer
a is [0 1 0 0 0 0 6 7 8 9]. The slice a[2:6] is a view, so b[:] = 0 writes zeros into positions 2 to 5 of a. The list index a[[6, 7]] is a copy, so c[:] = 9 changes only c and positions 6 and 7 of a stay 6 and 7.
Exercise
A colleague writes scores[scores < 50][0] = 50 to raise the first failing score to 50. It runs without error but scores is unchanged. Explain why and give a one-line fix that raises every failing score to 50.
Show answer
scores[scores < 50] uses a boolean mask, so it returns a copy. The [0] = 50 then writes into that temporary copy, which is discarded. To raise every failing score, assign through the mask in one operation: scores[scores < 50] = 50.
Exercise
You load a 500 MB array data and need to keep only data[:100] for a long-running process. What should you write, and which attribute shows that your result owns its memory?
Show answer
Write head = data[:100].copy(). After that, head.base is None (equivalently head.flags.owndata is True), so head no longer keeps the 500 MB buffer alive and data can be freed.