Swapping Variables and Multiple Assignments

We can perform multiple assignments simoultaneously. For example, to assign 42 to a and 43 to b, we can go:

In [2]:
a, b = 42, 43
In [3]:
a
Out[3]:
42
In [4]:
b
Out[4]:
43

This will come in handy in a second. Here's a problem: suppose we want to swap the values of a and b. That is, we want a to contain what b used to contain, and vice versa. Here is an idea that won't work:

In [5]:
a, b = 42, 43

a = b
b = a
print(a, b)
43 43

Why didn't this work? Because once we go a = b, the value that a used to contain is lost. b = a will do nothing. One solution is to use a temporary variable so as not to lose the value that a used to contain forever:

In [6]:
a, b = 42, 43
tmp = a
a = b
b = tmp

print(a, b)
43 42

But there is an easier way: use multiple assignment:

In [7]:
a, b = 42, 43

a, b = b, a  #simoultaneously assign the value of b to a, and the value of a to b
print(a, b)
43 42