Skip to content

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 tuple
empty = ()
no_paren = 1, 2, 3 # parentheses are optional — the comma makes a tuple

Because a tuple cannot change, it can be used as a dictionary key or stored in a set — a list cannot.

# Valid — tuples are hashable
visited = {(0, 0), (1, 2), (3, 4)}
grid = {(0, 0): "start", (3, 4): "end"}
# TypeError — lists are not hashable
bad = {[0, 0]: "start"}
# Packing
coords = 10, 20 # (10, 20)
# Unpacking
x, y = coords # x=10, y=20
# Extended unpacking
first, *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 variable
a, b = 1, 2
a, b = b, a # a=2, b=1

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 4
print(p[0], p[1]) # 3 4 — still indexable like a regular tuple
print(p) # Point(x=3, y=4)
# Immutable just like a plain tuple
p.x = 99 # AttributeError

Both give named fields; the difference is mutability and ergonomics:

Featurenamedtuple@dataclass
Mutable by default
Hashable / dict keyonly if frozen=True
Indexable by position
Default valuesvia defaults=
Methods / validationawkward

Use namedtuple for lightweight, value-like records (coordinates, RGB, database rows). Use @dataclass when you need methods or mutable state.