When you select parts of data in numpy arrays, it often gives you a view, not a new copy. This means changes to the view affect the original data. This helps save memory and time.
0
0
Indexing returns views not copies in NumPy
Introduction
You want to quickly look at or change a part of a big dataset without copying it.
You want to save memory when working with large arrays.
You want to update parts of your data and see the changes reflected everywhere.
You want to avoid slow operations caused by copying data unnecessarily.
Syntax
NumPy
view = original_array[start:stop]
Indexing with slices usually returns a view, not a copy.
Modifying the view changes the original array too.
Examples
Changing the view changes the original array because the view shares the same data.
NumPy
import numpy as np arr = np.array([1, 2, 3, 4, 5]) view = arr[1:4] view[0] = 20 print(arr)
The slice from index 2 to end is a view. Changing it updates the original array.
NumPy
import numpy as np arr = np.array([10, 20, 30, 40]) slice_view = arr[2:] slice_view[1] = 99 print(arr)
Using
.copy() creates a new array. Changing it does not affect the original.NumPy
import numpy as np arr = np.array([5, 6, 7, 8]) copy = arr[1:3].copy() copy[0] = 100 print(arr)
Sample Program
This program shows that slicing returns a view that changes the original array. Using .copy() makes a separate array that does not affect the original.
NumPy
import numpy as np # Create an array arr = np.array([1, 2, 3, 4, 5]) # Get a view by slicing view = arr[1:4] # Change the first element of the view view[0] = 20 # Print original array to see the change print(arr) # Now create a copy copy = arr[1:4].copy() # Change the first element of the copy copy[0] = 99 # Print original array again to show no change print(arr)
OutputSuccess
Important Notes
Not all indexing returns views. Fancy indexing (like using lists or boolean arrays) returns copies.
Always use .copy() if you want to avoid changing the original data.
Summary
Indexing slices usually return views that share data with the original array.
Changing a view changes the original array.
Use .copy() to make a separate array if needed.