In Python,
a, b = b, a
effectively swaps the values a
and b
. More precisely, the name a
will now reference the value that was previously referenced by b
and vice versa.
This is called tuple packing/unpacking. The comma builds tuples; the swapping is done by the =
.
What happens "behind the scenes" is this:
- The tuple
b, a
is evaluated. You can imagine the result of this evaluation to be stored in an unnamed temporary variable. Let's call that variable temp
.
- The assignment operator
=
now causes temp
to be assigned to the name(s) on the left side of the =
. If there had been just one name on the left, as in x = b, a
, then x
would have been assigned the tuple b, a
.
- Since there is more than one name on the left side,
temp
will be "unpacked" into these names in sequence.
a
will be assigned the value of temp[0]
(which holds the value that b
pointed to), and b
will be assigned the value of temp[1]
.
Note that the number of names on both sides must match:
>>> a = 1
>>> b = 2
>>> c = 3
>>> a, b = c, b, a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
But you can use the tuple packing operator *
to tell Python to pack the remaining values into a single name:
>>> a, *b = c, b, a
>>> a
3
>>> b
[2, 1]