In [639]: arr = np.arange(10)
By indexing with a slice (basic indexing), arr2
is a view
of arr
. It shares the data buffer with arr
:
In [640]: arr2 = arr[5:8]
In [641]: arr2
Out[641]: array([5, 6, 7])
If we make a copy, values are copied, not shared:
In [642]: arr3 = arr[5:8].copy() # arr[[5,6,7]] is also a copy
By modifying arr2
in-place, we also modify part of arr
:
In [643]: arr2 *= 10
In [644]: arr2
Out[644]: array([50, 60, 70])
In [645]: arr
Out[645]: array([ 0, 1, 2, 3, 4, 50, 60, 70, 8, 9])
But not arr3
:
In [646]: arr3
Out[646]: array([5, 6, 7])
arr2 = arr2*10
does not modify the arr2
array, but rather assigns a whole new array to the arr2
variable.
So you need to understand what it means to assign an object to a variable. The difference between assign a variable, and modifying a mutable object. And the difference between array copy and view (and between basic and advanced indexing). This last one is specific to numpy
, the rest to Python as well.