Tuples and unpacking

Python · Essentials · 7 min

Tuples are how Python returns several values and represents small fixed records.

A tuple is an immutable sequence, usually written with parentheses: point = (3, 4). It's the comma that makes the tuple, not the parentheses: t = 1, 2 is a tuple, and a one-element tuple needs a trailing comma, (5,), because (5) is just the number 5 in brackets. () is the empty tuple.

You index and slice tuples like lists, but you can't append, remove or assign items. Use a tuple when the position has meaning — a coordinate, an RGB colour, a (name, age) row — and a list when you have a variable number of similar items.

Because they are immutable (and hashable, if their items are), tuples can be dictionary keys and set members: distances[("Paris", "Rome")] = 1105.

Unpacking assigns the items of any iterable to several names at once:

  • x, y = point
  • first, *rest = [1, 2, 3, 4] puts the leftovers in a list (rest == [2, 3, 4])
  • for name, age in rows: unpacks each row inside the loop

Functions "return multiple values" by returning a tuple, which the caller unpacks: q, r = divmod(17, 5). When a tuple has many fields, readability suffers (row[3] says nothing); that is when collections.namedtuple, typing.NamedTuple or a dataclass become worth it.

Note that a tuple's immutability is shallow: a tuple containing a list can't be rebound to another list, but the list inside can still change.

Example

point = (3, 4)
x, y = point
print(x, y)               # 3 4

single = (5,)
print(type(single), type((5)))   # <class 'tuple'> <class 'int'>

def min_max(values):
    return min(values), max(values)   # returns a tuple

lo, hi = min_max([7, 2, 9])
print(lo, hi)             # 2 9

first, *rest = [1, 2, 3, 4]
print(first, rest)        # 1 [2, 3, 4]

distances = {("Paris", "Rome"): 1105}
print(distances[("Paris", "Rome")])   # 1105

rows = [("Ana", 31), ("Ben", 27)]
for name, age in rows:
    print(f"{name} is {age}")

Remember

  • The comma makes a tuple; (x,) is a one-element tuple
  • Tuples are immutable and hashable, so they work as dict keys
  • Unpacking (a, *rest = ...) works with any iterable

Watch out for

  • Writing (5) and expecting a tuple.

Check yourself

  1. What is `type(("a"))`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences