Tuples
Overview
A tuple is like a list that can’t be changed. That sounds like a limitation, but it’s exactly what you want for values that belong together and shouldn’t drift apart: a point’s x and y, an RGB colour, a date’s year, month and day. Tuples also power one of Python’s nicest features: unpacking.
Creating tuples
point = (3, 4)
colour = (255, 128, 0)
person = ("Asha", "IN", 29)
also_a_tuple = 3, 4 # the commas make the tuple; brackets are optional
single = (5,) # one item: the comma is required
not_a_tuple = (5) # just the number 5 in brackets
empty = ()Indexing, slicing, len, in, looping, count and index all work exactly as with lists:
person[0] # 'Asha'
person[-1] # 29
len(colour) # 3Tuples are immutable
point[0] = 10TypeError: 'tuple' object does not support item assignmentThere’s no append or remove either. To “change” a tuple, build a new one: point = (10, point[1]).
Why would you want that?
- Safety — a tuple passed around your program can’t be altered by accident.
- Meaning — a tuple says “these values are one record of fixed shape”.
- Usable as keys — tuples can be dictionary keys and set members (lists can’t), e.g.
distances[("London", "Paris")] = 344.
Unpacking
Unpacking assigns each item of a tuple (or any sequence) to its own name, in one line:
point = (3, 4)
x, y = point
print(x, y) # 3 4
name, country, age = ("Asha", "IN", 29)The number of names must match the number of items:
x, y = (1, 2, 3)ValueError: too many values to unpack (expected 2, got 3)(Python 3.14 and earlier leave out the “, got 3” part.)
You’ve already seen unpacking at work:
a, b = b, a # swap: builds the tuple (b, a), then unpacks it
for position, item in enumerate(items): # enumerate gives (position, item) tuples
for name, score in zip(names, scores): # zip gives (name, score) tuples
minutes, seconds = divmod(135, 60) # divmod returns a tupleStar unpacking
A name with * collects “everything else” into a list:
first, *rest = [1, 2, 3, 4] # first = 1, rest = [2, 3, 4]
*start, last = [1, 2, 3, 4] # start = [1, 2, 3], last = 4
head, *middle, tail = "abcde" # 'a', ['b', 'c', 'd'], 'e'The starred name can be empty: a, *b = [1] gives b = [].
Ignoring values
Use _ for items you don’t need:
name, _, age = ("Asha", "IN", 29)Tuples as records
A list of tuples is a simple way to store table-like data:
students = [
("Asha", 91),
("Ben", 78),
("Chen", 85),
]
for name, score in students:
print(f"{name}: {score}")Position-based access gets confusing as records grow (student[3] — what was item 3?). For records with more than a few fields, Dataclasses gives each field a name.
Functions that return several values
A function can return a tuple, and the caller unpacks it:
lowest, highest = min(scores), max(scores)
quotient, remainder = divmod(17, 5) # (3, 2)You’ll write your own in Return values and scope.
Tuple or list?
| Use a tuple when… | Use a list when… |
|---|---|
| the number of items is fixed | items are added or removed |
| each position means something different (name, age, city) | every item is the same kind of thing |
| it should never change | you’ll sort or edit it |
| you need a dict key or set item | — |
A good rule: lists for collections of similar things, tuples for small fixed groups of related things.
Remember: commas make tuples; tuples can’t change; and unpacking lets you take them apart into well-named variables.
Race results
Each runner is stored as a tuple (name, country, seconds). (1) Loop over the results with unpacking and print each runner as Asha (IN): 21 min 5 s, using divmod to split the seconds. (2) Using star unpacking on the list (sorted by time), get the winner, the runner-up and others, and print the winner’s name and how many others there were. (3) Try to change the first runner’s time with results[0][2] = 1200 inside a try block and print the error type name. (4) Build a tuple of the countries in finishing order and print it.
results = [
("Ben", "GB", 1302),
("Asha", "IN", 1265),
("Chen", "CN", 1290),
("Dee", "US", 1355),
]
# Sort by time (the third item) — explained in "Functions as values"
results.sort(key=lambda r: r[2])
# 1. Print each runner
# 2. Winner, runner-up, others
# 3. Try to change a tuple
try:
pass # replace with results[0][2] = 1200
except TypeError as error:
print(type(error).__name__)
# 4. Countries in finishing orderresults = [
("Ben", "GB", 1302),
("Asha", "IN", 1265),
("Chen", "CN", 1290),
("Dee", "US", 1355),
]
# Sort by time (the third item) — explained in "Functions as values"
results.sort(key=lambda r: r[2])
# 1. Print each runner
for name, country, seconds in results:
minutes, secs = divmod(seconds, 60)
print(f"{name} ({country}): {minutes} min {secs} s")
# 2. Winner, runner-up, others
winner, runner_up, *others = results
print("Winner:", winner[0], "| others:", len(others))
# 3. Try to change a tuple
try:
results[0][2] = 1200
except TypeError as error:
print(type(error).__name__)
# 4. Countries in finishing order
countries = ()
for name, country, seconds in results:
countries += (country,) # builds a new, longer tuple each time
print(countries)Summary
- A tuple is an ordered, unchangeable sequence:
(3, 4)or just3, 4; a one-item tuple needs a comma:(5,). - Unpacking assigns each item to a name:
x, y = point; the counts must match. - Star unpacking collects the rest into a list:
first, *rest = items. - Use tuples for fixed groups of related values (a point, a record, a function’s several results), lists for collections that change.
- Tuples can be dictionary keys and set items; lists can’t.