Python 101Free
DATA STRUCTURES

Tuples

Immutable, fixed shape records.

SECTION 01

The tuple model

A tuple is a fixed-length, immutable sequence. The shape is decided at creation time and cannot change. Trying to assign into a tuple raises TypeError. The only way to "modify" a tuple is to build a new one.

Use a tuple when position has meaning. A point is (x, y), a database row is (id, name, created_at), a return value with multiple parts is (result, error). The fixed shape is the point: it tells the reader the shape is part of the contract.

Because tuples are immutable, they are also hashable. This means you can use them as dictionary keys or as members of a set, which is something you cannot do with a list.

python
point = (3, 7)
# point[0] = 9       # TypeError: tuples are immutable

seen = {(3, 7), (0, 0)}   # tuples can live in a set
SECTION 02

Packing and unpacking

Packing is what happens implicitly: point = 3, 7 builds a tuple of two elements. The parentheses are optional in many contexts, the comma is what makes it a tuple.

Unpacking goes the other direction: a, b = point extracts the two elements into separate names. The number of names on the left must match the number of values on the right. If you only need some of them, use _ as a placeholder, or use star-unpacking.

The star form, a, *rest = [1, 2, 3, 4], binds a to 1 and rest to [2, 3, 4]. The starred name catches the rest of the elements. This works for any iterable, not just tuples, and is what you want when the length is variable.

python
a, b = 1, 2
a, b = b, a              # one-line swap

head, *rest = [1, 2, 3, 4]
# head = 1, rest = [2, 3, 4]
← PREVIOUS
Lists
NEXT →
Dictionaries