Copies vs Views
Python · NumPy Library
Theory
A view is a new array object that looks at the same memory as the original; a copy has its own data. Basic slicing returns a view, so part = prices[1:3] followed by part[0] = 0 also changes prices. Reshape, ravel and transpose usually return views too. Boolean masks and fancy indexing (prices[[0, 2]]) always return copies, and so does arr.copy().
Views make slicing big arrays cheap because nothing is duplicated, but they surprise beginners who expect a slice to be independent. To be safe, call .copy() when you plan to modify a piece and keep the original unchanged. np.shares_memory(a, b) tells you whether two arrays overlap, and arr.base is the original array for a view or None for an array that owns its data.
Why we use it
Silent changes to the original data are one of the hardest bugs to spot. Knowing which operations share memory lets you avoid accidental edits and also avoid unnecessary copies of large arrays.
When to use it
Use views (plain slices) when you only read data or deliberately want to edit the original block. Call .copy() before modifying a slice you want to keep separate, for example when cleaning a subset while keeping the raw data.
How it works
- Take part of an array
- Was it a basic slice (start:stop)? Yes: It is a view: shares memory. No: Mask or fancy index: it is a copy.
- Will you modify the piece? Yes: Call .copy() if the original must stay unchanged. No: A view is fine and saves memory.
- Edit safely
Syntax
view = arr[1:3]
copy = arr[1:3].copy()
np.shares_memory(a, b)
view.base is arrExample
prices = np.array([100, 200, 300])
part = prices[0:2]
part[0] = 0
print(prices) # [ 0 200 300]Key points
- Basic slices return views that share memory
- Boolean masks and fancy indexing return copies
- Use .copy() before editing a piece you want independent
- np.shares_memory(a, b) checks whether two arrays overlap
- pandas has the same idea, which is behind SettingWithCopyWarning