Views and copies
Last updated
Slicing a list makes a new list. Slicing an array doesn't: it gives you a second name for part of the same array. That makes NumPy fast, and it can also change data you thought you'd left alone. In this lesson you'll learn which operations share memory and which copy.
By the end of this lesson you can
- Explain what a view is, and that a slice is one
- Say which operations copy:
.copy()and fancy indexing - Check whether two arrays share memory with
np.shares_memory
Two names, one array
Step through what happens when you slice an array and change the slice.
a = np.array([45, 46, 45, 44, 47]): one array, one block of memory.A view is a new array object that looks at memory belonging to another array. Making one is almost free: no numbers are copied, however big the array. That's why slicing a million-row array takes no time.
What copies and what doesn’t
Run the cells, and watch a in each one.
b = a[1:4]is a view. Settingb[0] = 99changeda[1].np.shares_memory(a, b)isTrue.c = a[1:4].copy()is a copy. Changingcleftaalone.d = a[[1, 2, 3]]picks the same three elements by a list of positions (fancy indexing, lesson 2.5). That always copies, so it shares nothing. Masks copy too.- A Python list works the other way:
shopping[:2]is a new list, so changing it leavesshoppingalone. This is the habit you bring from Python, and it's the one that catches people out with NumPy.
The rule: slices are views; fancy indexing, masks and .copy() make copies. When you're not sure, ask np.shares_memory.
Wrong way: the first week
You want the first three days' prices with ₱5 off, to compare against the rest. Run the first cell, then the second.
first_week looks right. But prices has changed too: the first three are now 40, 41 and 40. first_week was a view, and -= changed its boxes, which are prices' boxes. Any total worked out from prices after this is wrong.
Fix it: change the first cell to first_week = prices[:3].copy(), then Restart and run all (the old prices is still in memory otherwise). Now prices keeps its real values.
The same problem exists in pandas, which used to warn about it with a confusing message. pandas 3 changed the rules so it can't happen there: lesson 3.6 shows how.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- NumPy: Copies and views: which operations make views, and which copy
- NumPy: numpy.shares_memory: checking whether two arrays overlap
- Harris et al., Array programming with NumPy, Nature 585, 2020: how slices are views onto the same data