Consider this problem — two students want to swap backpacks. In real life, this is pretty easy to do. But when we are swapping values of two variables, things are a little tricky. To explain, consider these rules:
- two students need to swap backpacks
- they can only hold one backpack at a time
What happens if we try to do a simple swap?
emma = 'blue backpack' lucy = 'red backpack' lucy = emma emma = lucy
When we set
lucy = emma, this makes
lucy point to ‘blue backpack’ and now
neither variable is pointing to ‘red backpack’. Setting
emma = lucy means
emma points to the same thing as
lucy — the blue backpack!
Solving the swap problem
To solve this problem, we need the help of a ‘third person’ or a third variable to hold one of the backpacks:
temp = lucy lucy = emma emma = temp
The Python way of swapping
The swapping solution above is used in many programming languages. In Python, we can use tuple unpacking to swap two variables:
emma, lucy = lucy, emma
This creates a tuple
(lucy, emma), and then unpacks the tuple into
emma, lucy. Python takes care of any temporary variables it uses while it
makes this swap.