We can perform multiple assignments simoultaneously. For example, to assign 42
to a
and 43
to b
, we can go:
a, b = 42, 43
a
b
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:
a, b = 42, 43
a = b
b = a
print(a, b)
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:
a, b = 42, 43
tmp = a
a = b
b = tmp
print(a, b)
But there is an easier way: use multiple assignment:
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)