I tried assigning three expressions in Python but I'm an unexpected result.
Let's begin with simple swaps. You probably know the result of this assignment:
A = [10, 11, 12]
p = 0
A[p + 1], A[p] = A[p], A[p + 1] # <--
print(A)
The result is (as expected):
[11, 10, 12]
Now I wanted to be a little more daring, so tried this assignment:
A = [10, 11, 12]
p = 0
p, A[p + 1], A[p] = p + 1, A[p], A[p + 1] # <--
print(A)
I thought that the result would be:
[10, 12, 11]
However, the result was:
[10, 11, 10]
Which is unexpected!
I read Python documentation regarding assignments:
Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. For instance, the following program prints [0, 2]:
x = [0, 1] i = 0 i, x[i] = 1, 2 # i is updated, then x[i] is updated print(x)
I did not get similar results for my swap. I don't understand the logic behind my swap. What's going on?
x[i++]=i++. Don't do it; even if the behavior is well defined, it may not be especially clear. Incrementp, then perform the swap.