I am reading numpy's documentation and in the section "basic indexing" there is an example that I am struggling to understand.
Documentation link: https://numpy.org/doc/stable/user/basics.indexing.html#basics-indexing
The code:
x = np.arange(0, 50, 10)
array([ 0, 10, 20, 30, 40])
x[np.array([1, 1, 3, 1])] += 1
Returns:
array([ 0, 11, 20, 31, 40])
I am scratching my head because I imagined that the left-hand side created a new array, not a view. And indeed it does:
np.shares_memory(x, x[np.array([1, 1, 3, 1])])
Returns:
False
Thus, I imagined that iadd (+=
) was being called on a new array, but that is not the case because somehow this operation is modifying the original array.
If I correctly understood the documentation, x[np.array([1, 1, 3, 1])]
triggers a "advanced indexing", which "always returns a copy of the data".
The "question": can someone help me understand that is going on here? A step-by-step description of what is going on would be appreciated.
edit: more specifically, what I imagined would happen:
- create a temporary new array with
[10, 10, 30, 10]
- try assign
[10, 10, 30, 10] + 1
to this new array - broadcast
1
to allow the summation - assign the result of the sum,
[11, 11, 31, 11]
, to the temporary array
Since there is no reference to this temporary array I imagined this would effectively be a noop.