장은수 - 4 months ago 20

Python Question

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`

`a`

My question is, if I first time assign

`a`

`x`

`x`

`a`

`a`

`x`

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)
```