Swapping variable values

Recall that we were able to swap variable values using multiple assignment.

In [1]:
a, b = 42, 43  #assign 42 to a and 43 to b
In [2]:
print(a, b)
42 43
In [3]:
a, b = b, a   #swap the values of a and b
print(a, b)
43 42

Suppose now that we don't want to use this trick. A naive approach would be:

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

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

What happenned? The moment we go a = b, both a and b become equal to 43. At this point, the line b = a is pointless. What's the problem there? It's that we are overwriting the information in a when we go a = b. So let's say that information before overwriting it

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

temp = a   #temp is the usual name for this kind of thing (for "temporary"). We are saving the old value of a in it.
a = b
b = temp
print(a, b)
43 42