0
0
NumPydata~10 mins

Indexing returns views not copies in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Indexing returns views not copies
Create original array
Index array to get subset
Subset is a view (shares data)
Modify subset
Original array changes too
If copy made, original unchanged
Indexing an array returns a view that shares data with the original array. Changing the view changes the original.
Execution Sample
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
view = arr[1:3]
view[0] = 20
print(arr)
Create an array, get a slice view, modify the view, and print original array to see change.
Execution Table
StepActionArray stateView stateNote
1Create arr[1, 2, 3, 4]N/AOriginal array created
2Create view = arr[1:3][1, 2, 3, 4][2, 3]View shares data with arr
3Modify view[0] = 20[1, 20, 3, 4][20, 3]Change in view affects arr
4Print arr[1, 20, 3, 4]N/AOriginal array shows updated value
💡 Execution ends after printing arr showing shared data change
Variable Tracker
VariableStartAfter Step 2After Step 3Final
arr[1, 2, 3, 4][1, 2, 3, 4][1, 20, 3, 4][1, 20, 3, 4]
viewN/A[2, 3][20, 3][20, 3]
Key Moments - 2 Insights
Why does changing the view also change the original array?
Because the view shares the same data buffer as the original array, so modifying the view modifies the original. See execution_table step 3.
Is the view a separate copy of the data?
No, the view is not a copy but a window into the original array's data. This is why changes reflect back. See execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 3, what is the value of arr after modifying view?
A[1, 2, 3, 4]
B[20, 3, 3, 4]
C[1, 20, 3, 4]
D[1, 3, 3, 4]
💡 Hint
Check the 'Array state' column at step 3 in execution_table
At which step does the view get created?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column for when view = arr[1:3] happens
If we changed view[0] without the view sharing data, what would happen to arr?
Aarr would also change
Barr would remain unchanged
Carr would become empty
Darr would raise an error
💡 Hint
Refer to the concept that indexing returns views, not copies, in variable_tracker
Concept Snapshot
Indexing a NumPy array returns a view, not a copy.
Modifying the view changes the original array.
Slices share the same data buffer.
To avoid this, use .copy() to make a separate copy.
Remember: view = window, copy = separate data.
Full Transcript
We start by creating a NumPy array arr with values [1, 2, 3, 4]. Then we create a view by slicing arr from index 1 to 3, which gives us [2, 3]. This view shares the same data as arr. When we modify the first element of the view to 20, the original array arr also changes at that position, becoming [1, 20, 3, 4]. Finally, printing arr shows the updated array. This happens because the view is not a copy but a window into the original data. To avoid this, one must explicitly create a copy.