Learning LibraryCore Coding LibraryTeens

Tuples in Python: fixed records you can unpack

A product's name, price, and cost belong together, and the set of three shouldn't be shuffled or extended by accident. That's a tuple: a small, fixed record.

The big idea

A tuple is an ordered, immutable sequence, written with parentheses, that's ideal for a fixed group of related values.

See it in code

1The basics

Parentheses make a tuple. You index it like a list, but you can't change it after it's made:

python
tee = ("Organic tee", 38, 14)

print("Name:", tee[0])
print("Price:", tee[1])
print("Fields:", len(tee))
Run it. One product as a record:
Name: Organic tee
Price: 38
Fields: 3

Trying tee[1] = 42 would raise a TypeError. That's the point: a record that can't be altered by a stray line elsewhere.

2A step further

Unpacking assigns each element to its own name in one statement, which reads far better than indexes:

python
tee = ("Organic tee", 38, 14)
name, price, cost = tee
print(f"{name}: ${price - cost} profit per item")

product, color, size = "TEE-SAGE-M".split("-")
print("Color:", color.title(), "| Size:", size)
Run it. Three values, three names:
Organic tee: $24 profit per item
Color: Sage | Size: M

Unpacking works on any sequence with the right number of items, including the list that split returns. The count on each side must match exactly.

3At Evergreen

A list of tuples is a simple table. Unpack right in the for line and each row arrives as named values:

python
catalog = [
    ("Organic tee", 38, 14),
    ("Everyday pants", 78, 29),
    ("Wool socks", 14, 4),
]

for name, price, cost in catalog:
    margin = (price - cost) / price
    print(f"{name}: {margin:.1%} margin")
Run it. A catalog of records:
Organic tee: 63.2% margin
Everyday pants: 62.8% margin
Wool socks: 71.4% margin

No indexes anywhere. Each row unpacks into name, price, and cost, so the body reads like the business logic it is.

The same idea, everywhere

Tuples turn up wherever values travel as a group: an (x, y) point, a (start, end) range on a chromosome, a (date, price) reading, the (key, value) pairs from a dictionary's .items().

Try it yourself

Swap two variables in one line with a, b = b, a, which is tuple packing and unpacking at work. Then add a fourth field, wears, to every record and compute cost per wear.

The common mistake

Mismatching the count when unpacking. name, price = tee raises ValueError: too many values to unpack, because the tuple has three items. Every element needs a name.

What it unlocks

Tuples are the fixed-size relative of lists, and they're what enumerate produces. When a record needs named fields and its own functions, it's time for a class.