I need to swap elements in a Python list. It works when I'm using a temporary variable to handle the swapping but doesn't seem to work when I do the same thing in a pythonic style, i.e. a, b = b, a
.
Suppose the index we are dealing with is i = 1
. I am trying to swap the elements at A[i] and A[A[i]]
.
Input A = [2,3,4,5,6,7,8,9] Expected Output = [2,5,4,3,6,7,8,9]
First I tried the pythonic way. Didn't get the expected output.
>>> i = 1
>>> A = [2,3,4,5,6,7,8,9]
>>> A[i], A[A[i]] = A[A[i]], A[i]
>>> A
[2, 5, 4, 5, 6, 3, 8, 9]
The non-pythonic way worked.
>>> i = 1
>>> B = [2,3,4,5,6,7,8,9]
>>> temp = B[B[i]]
>>> B[B[i]] = B[i]
>>> B[i] = temp
>>> B
[2, 5, 4, 3, 6, 7, 8, 9]
I just want to know why this is and when I should avoid using simultaneous assignment.