Tuples in Python
Tuples are immutable, ordered collections—great for fixed records and keys.
Creating tuples
Use literals, single‑element tuples (with trailing comma), or constructor.
empty = ()
pair = (1, "a")
single = (42,) # note trailing comma
from_iter = tuple([1, 2, 3])
Implicit packing/unpacking:
packed = 1, 2, 3 # tuple packing without parentheses
x, y, z = packed # unpacking
Indexing and slicing
Like lists, tuples support indexing and slicing.
t = (10, 20, 30, 40)
t[0], t[-1]
t[1:3] # (20, 30)
Unpacking patterns
Destructure with starred targets and nested structures.
x, y = (1, 2)
head, *mid, tail = (1, 2, 3, 4)
(a, (b, c)) = (1, (2, 3))
Immutability and safety
Tuples cannot be modified in place—useful for read‑only records and as dict keys.
points = {(0, 0): "origin", (1, 0): "x"}
If a tuple contains a mutable member, the overall tuple is only hashable if that member is hashable. Avoid mutable elements when using tuples as keys.
Named tuples
Give fields names for readability while retaining tuple behavior.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"]) # lightweight, indexable
p = Point(1, 2); p.x, p.y
typing.NamedTuple provides type‑annotated variants.
Dataclasses (alternatives)
For richer records with type hints and defaults, prefer @dataclass (mutable) or frozen=True (immutable‑like) to enforce read‑only behavior.
Summary
- Tuples are immutable sequences; good for fixed‑shape data and keys
- Use unpacking (including starred patterns) for clarity; named tuples or dataclasses for readable records