Tuples
Immutable ordered sequences for fixed collections and unpacking
Overview
Tuples are ordered, immutable sequences. Use them for fixed-size records, function return values, and dict keys. Immutability makes tuples hashable when their elements are hashable.
Syntax / Usage
# Create
point = (10, 20)
single = (42,) # trailing comma required for one-element tuple
mixed = ("Ada", 36, True)
# Access
point[0] # 10
point[-1] # 20
# Unpacking
x, y = point
first, *rest = (1, 2, 3, 4) # first=1, rest=[2,3,4]
# Named tuples (collections module)
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x # 3
Examples
Return multiple values from a function:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 9, 4])
Use a tuple as a dict key for a sparse grid:
grid = {}
grid[(0, 0)] = "start"
grid[(2, 1)] = "treasure"
Common Mistakes
- Creating
(42)instead of(42,)—parentheses alone do not make a tuple - Trying to mutate tuple elements when they contain mutable objects (the list inside can change)
- Using lists when immutability and hashability are required
- Overusing tuples where a
dataclassorNamedTupleimproves readability
See Also
python-dictionaries python-sets python-functions