Swapping variable valuesΒΆ

Suppose

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

We've see the following options for swapping their values. One is using multiple assignment:

In [2]:
a, b = b, a

Another is using a temporary variable:

In [3]:
temp = b
b = a
a = temp

Here is how we can swap the values of two integer variables without using either of those tricks:

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

#Suppose a == a', b = b'. That is, a' is the "old" value of a, and b' is the "old" value of b

a = a + b  #a == a' + b', b == b'
b = a - b  #a == a' + b', b == a'
a = a - b  #a == b', b == a'