Python foundations

Python Tuples: Creation, Unpacking, and Tuple Keys

Create a one-item tuple, unpack a pair, and see why a tuple can hold a list but cannot always serve as a dictionary key.

A Python tuple is an ordered sequence with fixed slots. Use it for values that belong together, such as the column and row of a tile. Write (4, 7) for a pair and ("north",) for a single item. The trailing comma makes that second example a tuple.

tile = (4, 7)
column, row = tile
assert (column, row) == (4, 7)
assert len(("north",)) == 1
assert () == tuple()

("north") is just a string in parentheses. Add a comma to get ("north",). Python also forms a tuple from a comma-separated expression such as column, row. Keep the parentheses when they make the boundaries of the tuple easier to see. The empty tuple is written ().

Understand what stays fixed

An immutable tuple keeps the same references in the same positions. It can hold a mutable object. That object can still change if you have a reference to it, including one you obtain by indexing the tuple.

notes = []
record = ("revision-2", notes)
notes.append("Spelling corrected")
assert record[1] == ["Spelling corrected"]

record[1] = [] would raise TypeError because it tries to replace the reference in that slot. Appending to the list changes the list itself. If you want a stable snapshot for simple string notes, store tuple(notes) at the moment you make the snapshot. As with a list copy, converting the outer collection does not recursively freeze nested mutable values.

Unpack when positions carry known meaning

first, second = pair gives two names to the entries. Python checks that there are two values to distribute. Too few or too many raises ValueError. Unpacking also works on other iterables, so a pair-shaped return value or an item from dict.items() can be read the same way.

A starred target collects extra entries into a list. first, *middle, last = ("a", "b", "c", "d") gives middle the list ["b", "c"]. Use exact unpacking when you intend to enforce a shape. Accept a starred remainder when the format deliberately allows extra entries.

Functions sometimes return a pair of related results. If each caller can understand width, height = size immediately, a tuple makes sense. Once a return value has several similar fields or keeps growing, a named record is easier to read. For example, dimensions.height describes its field without requiring the reader to count slots.

When a tuple can be a dictionary key

Dictionary keys and set members must be hashable. A tuple of integers, strings, or compatible immutable values can be a key. A tuple that contains a list is unhashable because the list cannot contribute a stable hash.

colors = {(4, 7): "gold", (4, 8): "blue"}
assert colors[(4, 7)] == "gold"
assert (7, 4) not in colors

Order matters to tuple equality. A coordinate represented by (4, 7) is distinct from (7, 4). If you only care which labels are present, a set fits that question. Use a frozenset if the group of labels itself needs to be a dictionary key.

Compare tuple, list, and named records

A list suits a changing series of values. A tuple makes the shape of a tiny positional result stable. A named tuple or dataclass can carry greater meaning when readers work with several fields. You can also use a dictionary when the field names are themselves part of the data, such as JSON-derived records with optional entries.

One final boundary to check is serialization. The JSON data model has arrays and objects, but no Python tuple type. A tuple encoded as a JSON array normally decodes as a Python list. If your application depends on tuple-shaped coordinates or key hashing, reconstruct tuples at the boundary after validating what came back.

Sources and further reading

Related reading

Browse Python foundations · Explore project tutorials

Search PythonProjects.org