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
Parentheses make a tuple. You index it like a list, but you can't change it after it's made:
tee = ("Organic tee", 38, 14)
print("Name:", tee[0])
print("Price:", tee[1])
print("Fields:", len(tee))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.
Unpacking assigns each element to its own name in one statement, which reads far better than indexes:
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)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.
A list of tuples is a simple table. Unpack right in the for line and each row arrives as named values:
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")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.
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.