📋 Lists & Tuples, lesson 6 of 6
Tuples and unpacking
Group fixed values in tuples and unpack them into variables.
9 min
1 exercise
3 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
A tuple is like a list that can't change
(immutable). Write it with parentheses:
point = (3, 4). Use tuples for small, fixed groups:
coordinates, RGB colors, a (name, score) pair.
Indexing, slicing, len and in all work.
Points and colors
Make your own color tuple, e.g. (0, 128, 255).
Tuples can't change
To "change" a tuple, make a new one: point = (10, point[1]).
What does this print?
Unpacking assigns each item to its own variable in
one go: x, y = point. The number of names must
match the number of items, unless you use a
starred name (*rest) to collect the leftovers.
It also gives Python its famous one-line swap:
a, b = b, a.
Unpacking tricks
Try *others, last = [...] to grab the last item instead.
Loop over pairs
Each tuple is unpacked into name and score on every pass.
What does this print?
Trip planner
trip lists (city, nights) tuples. Loop over it
with unpacking (for city, nights in trip:) to:
- Add up all nights in
total_nights. - Store the city with the most nights in
longest.
When is a tuple a better choice than a list?