Sub topic 6
Views versus copies
This chapter assumes you can create arrays, read shape and strides, and use basic slicing such as a[1:4]. It covers which NumPy operations share memory with the original array, which allocate new memory, and the bugs that follow when you guess wrong.
The working model: header plus buffer
An ndarray has two parts. The buffer is a block of memory that holds the elements. The header holds the metadata: a pointer into the buffer, the dtype, the shape, and the strides.
- A view is a new header that points at the same buffer. Creating it costs almost nothing, and writes through either array are visible in both.
- A copy has its own buffer. The two arrays are independent after creation.
Python lists work differently. Slicing a list always copies the references into a new list. Slicing an ndarray usually does not copy, which is why NumPy slicing is cheap and also why it can surprise you.
Which operations return which
The rule of thumb is that anything NumPy can describe by changing only the header gives a view. Anything that needs elements in a new arrangement gives a copy.
| Operation | Result | Notes |
|---|---|---|
| `a[1:4]`, `a[::2]`, `a[:, 0]` | View | Basic slicing: integers, slices, `None`, `...` |
| `a.T`, `a.transpose()`, `a.swapaxes(0, 1)` | View | Only the strides change |
| `a.reshape(...)` | View if possible, otherwise copy | Depends on memory layout |
| `a.ravel()` | View if possible, otherwise copy | `flatten()` always copies |
| `a.view()`, `np.squeeze(a)`, `a[np.newaxis]` | View | Header changes only |
| `a[[0, 2]]` (integer list or array) | Copy | Fancy indexing |
| `a[a > 0]` (boolean mask) | Copy | Result is a new 1-D array |
| `a.copy()`, `a.astype(...)` | Copy | `astype` copies by default |
| `np.concatenate`, `np.stack`, `a + 1` | Copy | New array with new data |
Seeing sharing directly
Do not guess. Check with np.shares_memory, which tests whether two arrays overlap in memory. The base attribute and the owndata flag also show where an array's data comes from.
import numpy as np
a = np.arange(6)
s = a[1:4] # basic slice: view
print(s.base is a) # True
print(s.flags.owndata) # False
print(np.shares_memory(a, s)) # True
f = a[[1, 2, 3]] # integer-list indexing: copy
print(np.shares_memory(a, f)) # False
s[0] = 99
print(a) # [ 0 99 2 3 4 5]
print(f) # [1 2 3], unaffectednp.may_share_memory is a faster, conservative check that can return True for arrays that only overlap in bounds. Use shares_memory when you need an exact answer.
Reshape: sometimes a view, sometimes not
reshape returns a view whenever the new shape can be expressed with strides over the existing buffer. Otherwise it quietly returns a copy. Both calls look the same, so the behavior depends on the array's layout.
import numpy as np
a = np.arange(6)
r = a.reshape(2, 3)
print(np.shares_memory(a, r)) # True: contiguous data, view
t = r.T # shape (3, 2), strides swapped
flat = t.reshape(6) # needs order 0, 3, 1, 4, 2, 5
print(np.shares_memory(t, flat)) # False: NumPy had to copy
flat[0] = -1
print(r) # unchangedThe transposed array reads the buffer out of order, and no single stride can walk that order in a flat 1-D array. The same logic applies to ravel.
If your code depends on getting a view, assign to the shape attribute instead of calling reshape. That raises an AttributeError when a copy would be needed. Newer NumPy versions deprecate setting shape and recommend reshape(copy=False), which raises a ValueError in the same situation. Check which your installed version supports.
Mutation through views
Because a slice is a view, in-place operations on it modify the parent. This includes +=, *=, -=, and slice assignment.
import numpy as np
m = np.arange(6).reshape(2, 3)
row = m[0]
row *= 10
print(m)
# [[ 0 10 20]
# [ 3 4 5]]A common version of this bug is a helper function that normalizes its input in place.
import numpy as np
def center(x):
x -= x.mean() # modifies the caller's data
return x
data = np.array([1.0, 2.0, 3.0, 4.0])
part = data[:2]
center(part)
print(data) # [-0.5 0.5 3. 4. ]The function never touched data by name, yet data changed. To avoid this, write x = x - x.mean(), which allocates a new array, or call x.copy() at the top of the function. Pick one convention for your codebase and document it.
Fancy indexing: copies on read, in-place on write
Fancy and boolean indexing return copies when they appear on the right-hand side of an expression. When they are the target of an assignment, NumPy writes into the original array.
import numpy as np
a = np.array([3, -1, 4, -5, 9])
a[a < 0] = 0 # one assignment: modifies a
print(a) # [3 0 4 0 9]This leads to the classic chained-indexing bug.
import numpy as np
a = np.array([3, -1, 4])
a[a > 0][0] = 100 # a[a > 0] is a temporary copy
print(a) # [ 3 -1 4], unchangedPython evaluates a[a > 0] first, producing a copy, and then assigns into that temporary. The write is lost with no error. Compute the integer position first and assign in a single indexing step.
import numpy as np
a = np.array([3, -1, 4])
first = np.flatnonzero(a > 0)[0]
a[first] = 100
print(a) # [100 -1 4]Pandas users know this as SettingWithCopyWarning. NumPy gives you no warning at all.
Other edge cases
A small view keeps a large buffer alive. A view holds a reference to its base, so the whole buffer stays in memory.
import numpy as np
big = np.zeros((10_000, 10_000)) # about 800 MB
tiny = big[:2, :2].copy() # copy so big can be freed
del bigWithout .copy(), the 800 MB buffer would stay allocated for as long as tiny exists.
np.array copies, np.asarray does not. np.array(x) copies by default. np.asarray(x) returns x itself when it is already an ndarray with a compatible dtype. Functions that accept "array-like" input often use asarray, so they can return a view of your data or even your own array.
astype can skip the copy. a.astype(np.float64, copy=False) returns a itself when the dtype already matches. Without copy=False you always get a new array.
Some views are read-only. np.broadcast_to returns a view in which many positions point at the same element, so writing to it would be ambiguous.
import numpy as np
b = np.broadcast_to(np.arange(3), (2, 3))
print(b.flags.writeable) # FalseCopy it first if you need to modify it.
Decision criteria
- Use views when you only read the data or when you want writes to reach the original. They save time and memory.
- Use
.copy()before modifying a slice you intend to keep separate from its parent. - Use
.copy()when you keep a small slice of a large array for a long time. - In functions, either document that the argument is modified in place or avoid in-place operators on arguments.
Exercise
Given the code below, what does print(a[:5]) output, and why?
import numpy as np
a = np.arange(10)
b = a[::2]
c = a[[0, 2, 4]]
b[0] = 100
c[1] = 200
print(a[:5])
Show answer
It prints [100 1 2 3 4]. The step slice a[::2] is a view, so b[0] = 100 writes to a[0]. The list index a[[0, 2, 4]] is fancy indexing and returns a copy, so c[1] = 200 changes only c.
Exercise
Why does a[a > 0][0] = 100 leave a unchanged, and how do you set the first positive element correctly?
Show answer
a[a > 0] uses a boolean mask, so it returns a copy. The assignment then writes into that temporary array, which is discarded. Compute the position with i = np.flatnonzero(a > 0)[0] and assign with a[i] = 100, which writes into a itself.
Exercise
You run t = np.arange(6).reshape(2, 3).T and then flat = t.reshape(6). Does writing to flat change t? How can you confirm it in code?
Show answer
No. Flattening a transposed array cannot be expressed with one stride, so reshape returns a copy. Confirm with np.shares_memory(t, flat), which returns False.