You take a slice of an array, change a value in it, and suddenly your original data has changed too. It's one of the most confusing bugs for NumPy beginners, and it happens because some operations give you a view of the same data, while others give you a separate copy.
This lesson explains the difference, lists which operations return which, shows how to check, and gives simple rules so it never catches you out.
The difference in one example
A copy is a new array with its own data. A view is a new array object that looks at the same data in memory as the original:
import numpy as np
prices = np.array([100, 200, 300, 400])
view = prices[1:3] # a slice: view
copy = prices[1:3].copy() # an explicit copy
view[0] = 999
copy[1] = -1
print(prices) # [100 999 300 400]
Changing the view changed prices. Changing the copy didn't. Think of a view as a window onto a room: move the furniture through the window, and the room changes.
Why does NumPy do this?
Speed and memory. A dataset can be gigabytes. If every slice copied its data, simply looking at the first million rows would double your memory use. A view is created instantly and uses almost no extra memory, whatever the size of the array.
Python lists behave differently: slicing a list always copies. That's why this surprises people who learned lists first.
Which operations return a view?
| Operation | Returns |
|---|---|
Basic slicing: a[1:3], a[:, 0], a[::2] | View |
a.reshape(...) | View, when possible |
a.T, a.transpose() | View |
a.ravel() | View, when possible |
a.view() | View |
Fancy indexing: a[[0, 2]] | Copy |
Boolean indexing: a[a > 5] | Copy |
a.flatten() | Copy |
a.copy(), np.array(a) | Copy |
Arithmetic: a + 1, a * 2 | New array |
A simple way to remember it: if NumPy can describe the result as "the same data, read with a different start, step or shape", it gives a view. If it has to pick out scattered values, it must copy them.
How to check
np.shares_memory tells you whether two arrays use the same data:
a = np.arange(10)
print(np.shares_memory(a, a[2:5])) # True: slice
print(np.shares_memory(a, a[[2, 3, 4]])) # False: fancy index
print(np.shares_memory(a, a[a > 5])) # False: boolean index
A view also has a .base attribute pointing at the array that owns the data. For an array that owns its own data, .base is None:
b = a.reshape(2, 5)
print(b.base is a) # True: b is a view of a
print(a.base) # None: a owns its data
The bug this causes, and the fix
Here's a typical mistake. We want to normalise a copy of some marks for a chart, but keep the raw marks:
raw = np.array([[45.0, 80.0], [60.0, 95.0]])
maths = raw[:, 0] # a view of column 0
maths /= maths.max() # changes raw too!
print(raw)
[[ 0.75 80. ]
[ 1. 95. ]]
The raw marks are gone. The fix is one word:
raw = np.array([[45.0, 80.0], [60.0, 95.0]])
maths = raw[:, 0].copy()
maths /= maths.max()
print(raw[:, 0]) # [45. 60.] safe
Assignment is neither
Plain assignment doesn't create a view or a copy. It gives the same array a second name:
x = np.array([1, 2, 3])
y = x
y[0] = 50
print(x) # [50 2 3]
print(y is x) # True
This is normal Python behaviour, the same as with lists. Use y = x.copy() when you need two independent arrays.
In-place vs new arrays
Arithmetic like a + 1 always creates a new array, even when you assign it back to the same name. In-place operators like +=, *= and /= modify the existing data:
a = np.arange(5)
s = a[:2]
a = a + 10 # a now names a NEW array; s still sees the old one
print(s) # [0 1]
a = np.arange(5)
s = a[:2]
a += 10 # changes the data in place; s sees it
print(s) # [10 11]
Simple rules to stay safe
- Call
.copy()when you take a slice and plan to modify it but want the original unchanged. - Don't bother copying when you only read a slice: views are free, so enjoy them.
- Functions that modify their input should say so in their name or docs, or work on a copy.
- If data changes unexpectedly, check with
np.shares_memory.
pandas has the same idea, which is the source of its famous SettingWithCopyWarning. Understanding NumPy views makes that warning much less mysterious when you reach the pandas DataFrame tutorial.
Practice
- Will
achange?a = np.arange(6); b = a[a % 2 == 0]; b[0] = 100
Show the answer
No. Boolean indexing returns a copy, so a is still [0 1 2 3 4 5].
- Will
achange?a = np.arange(6); b = a.reshape(2, 3); b[0, 0] = 100
Show the answer
Yes. reshape returns a view here, so a[0] becomes 100. Check with np.shares_memory(a, b), which gives True.
- Write a function
centre(x)that returnsxminus its mean, without changing the caller's array.
Show the answer
def centre(x):
return x - x.mean() # creates a new array
data = np.array([1.0, 2.0, 3.0])
print(centre(data)) # [-1. 0. 1.]
print(data) # [1. 2. 3.] unchanged
Writing x -= x.mean() inside the function would change the caller's array.
Interview questions
What is the difference between a view and a copy in NumPy?
A view is a new array object that shares the original's data buffer, so changes through either are visible in both. A copy has its own data, so changes are independent. Views are fast and memory-free; copies cost time and memory.
Which NumPy operations return views?
Basic slicing, reshape and ravel (when the layout allows), transpose and .view(). Fancy indexing, boolean indexing, flatten and .copy() return copies.
How can you tell if an array is a view?
Check arr.base: for a view it refers to the array that owns the data, and for an array that owns its data it's None. np.shares_memory(a, b) checks whether two arrays overlap in memory.
What to learn next
- Review the basics in the NumPy array tutorial for beginners.
- Take your arrays into pandas with the pandas DataFrame tutorial.