Tuples and Unpacking
A tuple groups a few values that belong together, such as a city and its miles, and can't be changed once made, and unpacking gives each value its own name in one line, which is how a function returns two values and how two variables swap.
Apprentice · Python · Updated
After this lesson you can
- Group values that belong together in a tuple, and unpack a tuple into separate variables in an assignment or a for loop
- Return two values from a function as a tuple, and swap two variables in one line
Key takeaways
- A tuple groups a fixed set of values in round brackets, such as ("Denver", 540). You read its items by index, but you can't change them.
- Use a list for a collection that grows and shrinks, and a tuple for a small group whose positions each mean something.
- Unpacking, as in city, miles = leg, gives each item of a tuple its own name, and it needs exactly one name per item.
- A function returns two values by returning one tuple, return low, high, which the caller can unpack.
- a, b = b, a swaps two variables in one line.
Some values only make sense together: a city and the miles to reach it, a latitude and a longitude, a time's hours and minutes. You'll group values like these whenever a program passes them around as one thing, and you'll want to take them apart again without fuss. Python's tool for this is the tuple, and it's also how a function hands back more than one answer.
The example is a road trip from Chicago to the Grand Canyon, where each day's drive is a pair: the city you reach, and how many miles it takes.
Two lists that have to stay in step
Here's a first try, with the cities in one list and the miles in another:
cities = ["Omaha", "Denver", "Moab", "Grand Canyon"]
miles = [470, 540, 355, 330]
print(cities[1], miles[1])
Denver 540
It works while the two lists stay in step, item for item. Insert a stop into cities and forget miles, and every city after it is paired with the wrong distance, with no error to warn you. The city and its miles belong together, so they should travel together.
A tuple: values that belong together
A ticket stub has the row and the seat printed side by side, and nobody edits them. A tuple (read "TUP-ul"; "TOO-pull" is heard too) is like that: a fixed group of values in round brackets, such as ("Denver", 540). You read its items by index, like a list's:
leg = ("Denver", 540)
print(leg)
print(leg[0])
print(leg[1])
print(len(leg))
('Denver', 540)
Denver
540
2
What you can't do is change it. A tuple is immutable, so leg[1] = 410 stops with TypeError: 'tuple' object does not support item assignment, and a tuple has no append() or remove(). That's the point: a leg's city and its miles stay paired. So:
- use a list for a collection that grows and shrinks, such as the trip's stops;
- use a tuple for a small group whose positions each mean something, such as one leg's city and miles.
A list of tuples gives you both, one tuple per day: legs = [("Omaha", 470), ("Denver", 540)].
Unpacking: one name for each part
Reading leg[0] and leg[1] leaves the reader to remember which index is which. Unpacking gives each item its own name in one line: city, miles = leg is read "city and miles get leg", and the first name gets the first item, the second the second. It works in a for line too, unpacking each tuple as the loop reaches it:
legs = [("Omaha", 470), ("Denver", 540), ("Moab", 355), ("Grand Canyon", 330)]
city, miles = legs[1]
print(city, "is", miles, "miles from the night before")
for city, miles in legs:
print(city + ":", miles, "miles")
Denver is 540 miles from the night before
Omaha: 470 miles
Denver: 540 miles
Moab: 355 miles
Grand Canyon: 330 miles
The left side needs exactly one name per item. Give three names for a two-item tuple, as in city, miles, state = leg, and Python stops with ValueError: not enough values to unpack (expected 3, got 2).
Returning two values
A function returns one value. When it has two answers, it returns them as one tuple: return low, high makes the tuple (low, high), and the caller unpacks it into two names:
def shortest_and_longest(miles):
return min(miles), max(miles)
shortest, longest = shortest_and_longest([470, 540, 355, 330])
print("Shortest day:", shortest)
print("Longest day:", longest)
print(shortest_and_longest([470, 540, 355, 330]))
Shortest day: 330
Longest day: 540
(330, 540)
The last line shows what really comes back: one tuple, in round brackets. It's the comma that makes a tuple, so a return line doesn't need the brackets.
Swapping two variables
To swap the drinks in two cups, you need a third cup to hold one of them for a moment. Swapping two variables usually works the same way, with a third variable. Unpacking does it in one line, a, b = b, a: Python builds the tuple on the right first, from the values as they are, and then unpacks it into the names on the left:
driver = "Maya"
navigator = "Leo"
driver, navigator = navigator, driver
print("Driver:", driver)
print("Navigator:", navigator)
Driver: Leo
Navigator: Maya
Maya and Leo trade seats after lunch, with no third variable to keep track of.
Do it: work out a day's driving time
The trip planner shows each day's driving time in hours and minutes. At the trip's average speed of 60 miles an hour, each mile takes one minute.
miles: the day's miles, a whole number.
Your job: write the function drive_time(miles) so it returns two values as one tuple, (hours, minutes).
hoursis the number of whole hours the drive takes.minutesis the minutes left over after those whole hours, from 0 to 59.- A drive under an hour has 0 hours.
Worked through: 470 miles take 470 minutes. 470 minutes is 7 whole hours (420 minutes), with 50 minutes left over, so drive_time(470) returns (7, 50).
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Tuples keep values that belong together in one piece, and unpacking takes them apart into clear names, so a function can hand back several answers and the code that uses them reads like plain English.