As we all know, the pythonic way to swap the values of two items a
and b
is
a, b = b, a
and it should be equivalent to
b, a = a, b
However, today when I was working on some code, I accidentally found that the following two swaps give different results:
nums = [1, 2, 4, 3]
i = 2
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
print(nums)
# [1, 2, 4, 3]
nums = [1, 2, 4, 3]
i = 2
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
print(nums)
# [1, 2, 3, 4]
What is happening here? I thought in a Python swap the two assignments happen simultaneously and independently.
See also Multiple assignment and evaluation order in Python regarding the basic semantics of this kind of assignment.
See also Multiple assignment semantics regarding the effect and purpose of parentheses on the left-hand side of a multiple assignment.
a,b = b,a
andb,a = a,b
both give the same result. – Shiversa,b = b,a
– Unclothej = nums[i]-1; nums[i], nums[j] = nums[j], nums[i]
which is safer imho; but you figured that out I guess – Awrynums[i]-1
as an index, rather thani-1
for instance? – Metralgia[1, 2, 4, 3]
could become[1, 2, 3, 4]
. However, sincenums[2] == 4
, I thought it would be intersting to do it likenums[nums[2]-1]
instead of simply doingnums[3]
, and then I found this strange behavior. – Ecotypea, b = b, a
. It's name should be along the lines of "Order of operation on assignment", potentially referencing tuple unpacking. Same with the tags on this question. – Neurovascularnums[i], nums[i+1] = nums[i+1], nums[i]
? That code does not look like a swap. – Unmanned