Multiple assignment and swapping
🌍 In real life. You have juice in one glass and milk in another, and you want to swap them. You can't just pour the juice into the milk glass: it's full, and the drinks would mix. You need a third, empty glass to hold one drink while you move the other.
Swapping two variables has exactly the same problem, and Python has a neat trick for it. First, a related shortcut: filling several boxes in one line.
The idea in one sentence: Python can fill several names in one line, matching the names on the left to the values on the right in order, and a, b = b, a uses this to swap two values safely.
Its words:
- multiple assignment:
x, y = 1, 2fills two boxes at once - swap: exchange the values of two variables
temp: the usual name for a spare box that holds a value for a moment
Step by step, for x, y, z = 1, 2, 3:
- Python works out the whole right side: 1, 2, 3.
- It matches them to the names in order: the first value to the first name, and so on.
- So
xgets 1,ygets 2 andzgets 3.
x, y, z = 1, 2, 3
print(x, y, z)a = b = 0
print(a, b)Why the obvious swap fails. Writing a = b and then b = a loses a value: the first line throws the old value of a away, so by the second line there's nothing left to copy back.
a = "apple"
b = "banana"
a = b
b = a
print(a, b)How Python's swap works. In a, b = b, a, Python works out the whole right side first: it picks up the value of b and the value of a and holds both at once. Only then does it fill the boxes on the left. Because both values are held before anything is replaced, nothing gets lost. Watch it, and follow the tracker under the boxes:
a = "apple"
b = "banana"
a, b = b, a
print(a, b)Many languages use a spare box called temp instead. It works in Python too:
a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)Mistakes and edge cases.
- More values than names.
x, y = 1, 2, 3givesValueError: too many values to unpack (expected 2, got 3). - Fewer values than names.
x, y, z = 1, 2givesValueError: not enough values to unpack (expected 3, got 2). - The obvious swap.
a = bthenb = aleaves both boxes holding the same value. - The temp steps in the wrong order. With a spare box, save first:
temp = a, thena = b, thenb = temp. Starting witha = blosesabefore it's saved.
Quiz
What does this print?
x, y = 3, 8 print(y)What does this print?
a = b = 5 print(a + b)What does this print?
a, b = 1, 2 a, b = b, a print(a, b)Why doesn't
a = bfollowed byb = aswap two variables?- The first line throws away a's old value
- Python can't copy variables
- You must print them first
Which line causes an error?
x, y = 1, 2, 3 print(x)
Coding tasks
In one line, set
widthto 4 andheightto 6. Then printwidth * height.Swap
leftandright, so thatleftholds"R"andrightholds"L". Don't retype the letters: swap the variables.