Topic 47 of 64
Tuple Immutability
Overview
Tuples are immutable ordered sequences. Their immutability makes them hashable (usable as dict keys or set elements), slightly faster than lists, and the right choice for data that shouldn't change (coordinates, RGB values, DB records).
Syntax
python
# Creation
point = (3, 4)
single = (42,) # single-element needs trailing comma!
empty = ()
# Access (same as list)
point[0] # 3
point[-1] # 4
# Immutability
point[0] = 10 # TypeError! tuples are immutable
# Tuple as dict key (hashable)
grid = {(0, 0): "start", (1, 1): "end"}
# Named tuple
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
p.x # 3Common Pitfalls
- (42) is an int, NOT a single-element tuple — you must write (42,) with the trailing comma.
- A tuple containing a mutable object (e.g., a list) is technically 'immutable' but its contents can change — the tuple holds a reference, not a copy.
- Interview tip: Prefer tuples for heterogeneous fixed-length data (like DB rows) and lists for homogeneous variable-length collections.
Real-World Example
Return multiple values from a function using a tuple
example
python
def min_max(numbers: list[int]) -> tuple[int, int]:
return min(numbers), max(numbers)
low, high = min_max([5, 2, 8, 1, 9, 3])
print(f"Min: {low}, Max: {high}") # Min: 1, Max: 9
# Also usable in set
seen_pairs: set[tuple[int, int]] = set()
seen_pairs.add((1, 2))
seen_pairs.add((3, 4))