Confusion about when NumPy array slices are references and when they are copies

Viewed 2986

I have the following piece of code:

import numpy as np
arr = np.arange(10)
slice = arr[2:5]
slice[:] = 12
print(arr)
slice = slice / 2
print(arr)

The output will be:

[ 0  1 12 12 12  5  6  7  8  9]
[6. 6. 6.]
[ 0  1 12 12 12  5  6  7  8  9]

So the first time around slice is just a reference to part of arr so modifying it also changes the array, but the second time around it has become a copy of that part of the array and modifying it makes no difference in arr. Why does this happen? What makes slice = slice / 2 different?

2 Answers

Indexing with a slice object always returns a view (reference) of an array. Modifying the slice will modify the original array. In your second example you assign to the slice object. That does not modify the object. A new object is created with the specified values, in this case slice / 2. You can use /= to modify the object in place if that's the desired behavior, or index into the slice ([:]) which numpy interprets as modifying the entries at those indices.

You should assign the change by all using [:]

arr = np.arange(10)
slice = arr[2:5]
slice[:] = 12
print(arr)
slice[:] = slice / 2
[ 0  1 12 12 12  5  6  7  8  9]
print(arr)
[0 1 6 6 6 5 6 7 8 9]
Related