Tuples

Topic 2 of 5 in Collections6 min readBeginnerFree course

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

Python
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:

Python
person[0]         # 'Asha'
person[-1]        # 29
len(colour)       # 3

Tuples are immutable

Python
point[0] = 10
Text
TypeError: 'tuple' object does not support item assignment

There’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

Tuples and unpacking. point = (3, 4) is a tuple; x, y = point attaches the names x and y to its two items, so print(x, y) shows 3 4. Other uses: a, b = b, a swaps two variables; first, *rest = [1, 2, 3, 4] gives first=1 and rest=[2, 3, 4]; for name, score in pairs: unpacks inside a loop; and q, r = divmod(17, 5) takes apart a function’s tuple result.

Unpacking assigns each item of a tuple (or any sequence) to its own name, in one line:

Python
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:

Python
x, y = (1, 2, 3)
Text
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:

Python
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 tuple

Star unpacking

A name with * collects “everything else” into a list:

Python
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:

Python
name, _, age = ("Asha", "IN", 29)

Tuples as records

A list of tuples is a simple way to store table-like data:

Python
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:

Python
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.

Exercise

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.

Python
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 order

Summary

  • A tuple is an ordered, unchangeable sequence: (3, 4) or just 3, 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.