장은수 장은수 - 1 month ago 7
Python Question

Why doesn’t executing "a, x = x, a" twice result in a change of values?

While watching a video explaining about a quiz I found this code snippet:

a, x = x, a
a, x = x, a
print a
print x


The video says that the end result is
x
and
a
swap, and if we do that again, it's going to be in the original place which doesn't change the value of any variables.

My question is, if I first time assign
a
=>
x
and
x
=>
a
, then the value of code is not going to be changed even if we do the exact same code and assign the same value for the same variable as I did just before. But why does the video explain that the value of the
a
and
x
are going to be swapped twice and going to get the same value before executing the statement?

Answer

The syntax a,x = x,a swaps the values because the assignments to the right hand side of the assignment operator (=) are first evaluated and then assigned to their values, as explained here. It logically follows that if this operation is performed twice, then the second swap returns the variables to their original values.

Note that if instead you wrote a = x; x = a then a and x would both end up as the start value of x because each statement is evaluated sequentially from left to right.

This behavior is the same in Python 3 and 2.

Demonstration:

>>> a = 1
>>> x = 2
>>> a,x = x,a
>>> a,x
(2, 1)
>>> 
>>> a = 1
>>> x = 2
>>> a = x; x = a
>>> a,x
(2, 2)