11

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?

navidoo
  • 309
  • 2
  • 11
  • 4
    Someone asked this exact question a couple of days ago and there was a good answer... just looking for it. Well-written question though – YXD Feb 21 '13 at 00:00
  • 1
    Thanks @MrE. That answers my question. From what I understand now, the Python way of performing simultaneous assignments is not through invisible "buffers" (copies of RHS data), but via ordinary assignment to intermediate variables of the same type as the RHS objects. In the case of array slices, this intermediate assignment creates "views" of the two RHS objects, and as soon as the first assignment "to" one of the LHS slices is performed (which for the first time involves an actual copy), the other object's data is lost and both intermediate variables point to identical data. – navidoo Feb 21 '13 at 00:42
  • 1
    Too bad about the dupe -- this question is much better written. – Fred Foo Feb 21 '13 at 00:50
  • @larsmans agree, I was going to suggest someone edits the other question to improve it but I see you've done that. – YXD Feb 21 '13 at 09:48

0 Answers0