pythonnumpy

numpy array slice then assign to itself


Why the following code does not return [1,4,3,4]? Hasn't a already changed during the reversed order assignment?

a=np.array([1,2,3,4])
a[1::]=a[:0:-1]

The result is:

array([1, 4, 3, 2])

Solution

  • You're right that a changes during the assignment, which in turn affects the view whose elements you're assigning into a. If NumPy didn't have special handling for this case, you could indeed see array([1, 4, 3, 4]) as a result.

    However, NumPy checks for this case. If NumPy detects that the RHS of the assignment may share memory with the array being assigned to, it makes a copy of the RHS first, to avoid this kind of problem:

    if (tmp_arr && solve_may_share_memory(self, tmp_arr, 1) != 0) {
        Py_SETREF(tmp_arr, (PyArrayObject *)PyArray_NewCopy(tmp_arr, NPY_ANYORDER));
    }