Python Tuples
Tutorial 11 of 65 · pythondeck.com Python course
Tuples are ordered, immutable sequences - perfect for fixed records and multiple return values. They are hashable when all elements are hashable, so they can serve as dictionary keys or set elements.
Tuples are ordered, immutable sequences. They model fixed-length records, coordinates, and rows returned from functions when you need integrity guarantees without copying overhead.
Immutability applies to the tuple object, not necessarily to objects it references—a tuple of lists can still have its lists mutated unless you treat it as read-only by convention.
Literals: (1, 2) or 1, 2; singleton requires trailing comma: (42,).
Unpacking: x, y = point; star unpacking: first, *rest = seq.
Index and slice like lists but no assign to tuple slots.
Tuples are hashable if all elements are hashable—usable as dict keys.
Named tuples (collections.namedtuple) and dataclasses add field names.
Often returned from functions: return min_val, max_val.
Tuple packing and unpacking make multiple return values idiomatic without building a dict. For large tabular data, use dataclasses, NamedTuple, or pandas—not long positional tuples.
Immutability saves memory and enables hashing; convert to list if you need in-place edits.
*args collects positional parameters; named records beyond three fields deserve dataclasses, not bare tuples.
Creating a one-element tuple without comma: (42) is just int 42 in parentheses.
Assuming tuple immutability prevents mutating a list inside the tuple.
Using plain tuples for wide records—field order errors are silent.
Concatenating many tuples in a loop with += (quadratic copying)—use a list then tuple().
Use tuples for heterogeneous fixed structures; lists for homogeneous growable collections.
Prefer namedtuple or dataclass when more than two or three positional fields.
Return tuples for small multi-value results; document order in the docstring.
Use tuple(iterable) for a shallow immutable snapshot when exposing internal state.
Unpack into named variables at the call site when tuple arity is three or fewer.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates pack/unpack. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Pack/unpack
# Run in the REPL or save as a .py file and execute with python.
point = (3, 4)
x, y = point
print(x, y)
This sample walks through named tuple in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: Named tuple
# Run in the REPL or save as a .py file and execute with python.
from collections import namedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p.y, p)
Here is a hands-on illustration of as dict key. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: As dict key
# Run in the REPL or save as a .py file and execute with python.
edges = {(1, 2): 0.5, (2, 3): 1.7}
print(edges[(1, 2)])
The program below demonstrates tuple unpacking. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Tuples are immutable sequences — ideal for fixed records
coords = (40.7128, -74.0060) # latitude/longitude pair
lat, lon = coords # unpack into separate names
print(f"near ({lat}, {lon})") # f-string displays both
record = ("task", "done", 3) # label, status, priority
label, status, prio = record # three-way unpack
print(label, status, prio) # task done 3
singleton = (99,) # comma makes a one-tuple
print(singleton == (99,)) # True
merged = (1, 2) + (3, 4) # concatenation builds new tuple
print(merged) # (1, 2, 3, 4)
This sample walks through dict tuple keys in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Hashable tuples work as dictionary keys for sparse grids
cells = {} # map coordinate tuple -> value
cells[(0, 0)] = "start" # origin cell
cells[(2, 1)] = "treasure" # another coordinate
for key in sorted(cells): # deterministic iteration order
print(key, cells[key]) # print each entry
rgb = (255, 128, 0) # color triple
r, g, b = rgb # channel unpack
print(hex((r << 16) + (g << 8) + b)) # pack into hex color
print(len(rgb), max(rgb)) # tuple supports sequence ops