I'm trying to swap columns of a Numpy array using simultaneous assignments and I get an unexpected behavior:
A = arange(12).reshape(3,4)
print(A)
# prints [[ 0 1 2 3] Ok
# [ 4 5 6 7]
# [ 8 9 10 11]]
A[:,0], A[:,1] = A[:,1], A[:,0]
print(A)
# prints [[ 1 1 2 3] Not what intended (swap)
# [ 5 5 6 7]
# [ 9 9 10 11]]
Expected behavior: the "views" of the arrays on the RHS are both evaluated and then the assignment is performed by the target object on the LHS "copying" the contents of the RHS views into the new locations. I claim that copies are made in slice-to-slice assignments because of the following:
A = arange(12).reshape(3,4)
A[:,0] = A[:,1]
A[:,1] = array([99,99,99])
print A[:,0]
# prints: [1 5 9]
What actually happens: it seems that in simultaneous assignments of slices, ndarray evaluates and assigns the various terms on the RHS and LHS "one at a time": first A[:,0] = A[:,1]
and then A[:,1] = A[:,0]
.
Is this due to the ndarray class customizing simultaneous assignments in a way different from the standard python way?