Tuples
A tuple is an ordered, immutable sequence. Think of it as a list that has been locked.
point = (3, 4)rgb = (255, 128, 0)single = (42,) # trailing comma required for a 1-element tupleempty = ()no_paren = 1, 2, 3 # parentheses are optional — the comma makes a tupleWhy immutability matters
Section titled “Why immutability matters”Because a tuple cannot change, it can be used as a dictionary key or stored in a set — a list cannot.
# Valid — tuples are hashablevisited = {(0, 0), (1, 2), (3, 4)}grid = {(0, 0): "start", (3, 4): "end"}
# TypeError — lists are not hashablebad = {[0, 0]: "start"}Tuple packing / unpacking
Section titled “Tuple packing / unpacking”# Packingcoords = 10, 20 # (10, 20)
# Unpackingx, y = coords # x=10, y=20
# Extended unpackingfirst, *rest = (1, 2, 3, 4, 5)# first=1, rest=[2, 3, 4, 5]
*head, last = (1, 2, 3, 4, 5)# head=[1, 2, 3, 4], last=5
# Swap without a temp variablea, b = 1, 2a, b = b, a # a=2, b=1Named tuples
Section titled “Named tuples”namedtuple gives each position a name, making code far more readable without adding overhead.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])Color = namedtuple("Color", ["red", "green", "blue"])
p = Point(3, 4)c = Color(255, 128, 0)
print(p.x, p.y) # 3 4print(p[0], p[1]) # 3 4 — still indexable like a regular tupleprint(p) # Point(x=3, y=4)
# Immutable just like a plain tuplep.x = 99 # AttributeErrornamedtuple vs dataclass
Section titled “namedtuple vs dataclass”Both give named fields; the difference is mutability and ergonomics:
| Feature | namedtuple | @dataclass |
|---|---|---|
| Mutable by default | ✗ | ✓ |
| Hashable / dict key | ✓ | only if frozen=True |
| Indexable by position | ✓ | ✗ |
| Default values | via defaults= | ✓ |
| Methods / validation | awkward | ✓ |
Use namedtuple for lightweight, value-like records (coordinates, RGB, database rows). Use @dataclass when you need methods or mutable state.