Python Tuples
A tuple is an ordered, immutable sequence. Great for "a record of related values" — coordinates, RGB triples, return values that group related data.
Create
PYTHON
point = (3, 4) single = (42,) # comma is required — (42) is just an int in parens empty = ()
Unpack
PYTHON
x, y = (3, 4) first, *rest = (1, 2, 3, 4, 5) # first=1, rest=[2,3,4,5] a, b = b, a # swap — classic idiom
Tuple vs list
| Tuple | List |
|---|---|
| Immutable | Mutable |
| Slightly faster | Slightly slower |
| Hashable — usable as dict keys, set members | Not hashable |
| "A record" | "A collection that can grow" |
Named tuples (nicer records)
PYTHON
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x, p.y, p) # 3 4 Point(x=3, y=4)
Modern alternative: dataclasses for mutable records, or typing.NamedTuple for typed immutable ones.
Tip: Functions can return multiple values via a tuple:
return name, age. The caller unpacks it: name, age = get_user().Example
Example
point = (3, 4) x, y = point # unpacking print(x, y) print(len(point)) # tuples are immutable # point[0] = 5 # would raise TypeErrorTry it Yourself »
Exercise
Make a single-element tuple containing 42.
t = (42
)
A single character; without it, this is just an int in parens.
Discussion
Loading…