Tuples
A tuple is an immutable ordered sequence. Once built, you cannot add, remove, or replace its elements, which makes a tuple of immutable values usable as a dictionary key or a set member.
Detailed Explanation
A tuple is laid out much like a list: a contiguous block of pointers to objects. The difference is that the block is allocated once, at exactly the right size, and never grows. There is no capacity field and no over-allocation, so a tuple of ten items uses less memory than a list of the same ten items.
Immutability is the point, not the small memory win. Because the pointers can never change, CPython can compute a hash from the elements, which means a tuple can be a dictionary key. That single property drives most real uses. You are caching a distance lookup keyed by (origin_airport, destination_airport). You are counting events keyed by (date, status_code). A list cannot do this job, because a list's contents could change after insertion and the hash table would lose track of it.
The second real use is grouping values that travel together. A function that needs to return both a parsed value and a flag returns (value, ok). Python then lets you unpack it back into names: value, ok = parse(line). Tuple unpacking is why for index, name in enumerate(names) reads the way it does, and why swapping is written a, b = b, a.
Rule: tuples are immutable. Exception, and it catches everybody: the immutability is shallow. A tuple freezes which objects it points at, not what those objects contain. config = ([1, 2], "prod") will let you call config[0].append(3), because the list itself is still mutable. The tuple is unchanged; it still points at the same list. But hash(config) now raises TypeError, because hashing a tuple hashes its elements and a list has no hash. A tuple is hashable only if everything inside it is hashable.
| Operation | Average | Worst case | Why |
|---|---|---|---|
record[i] | O(1) | O(1) | Pointer arithmetic into a fixed block |
len(record) | O(1) | O(1) | Length is stored |
x in record | O(n) | O(n) | Linear scan, same as a list |
hash(record) | O(n) | O(n) | Combines the hash of every element |
a + b | O(n + m) | O(n + m) | Builds a whole new tuple |
record[a:b] | O(k) | O(k) | Copies k pointers into a new tuple |
| append or insert | — | — | Does not exist; tuples cannot grow |
Because tuples cannot grow, building one element at a time is quadratic: each += allocates a new tuple and copies everything. Accumulate in a list, then call tuple(items) once at the end if you need an immutable result.
Two syntax notes. It is the comma that makes a tuple, not the parentheses, so point = 3, 4 is a tuple and a one-element tuple must be written (3,). And (3) is the integer three in brackets. Finally, a tuple's fields are positional, so record[2] tells a reader nothing; once a tuple has more than about three fields, a namedtuple or a dataclass is clearer.
Code Examples
# The comma builds the tuple; parentheses only group.
origin_destination = "DEL", "BOM"
single = ("DEL",) # trailing comma required for one element
not_a_tuple = ("DEL") # this is just the string "DEL"
print(type(single), type(not_a_tuple)) # <class 'tuple'> <class 'str'>
# Tuples are hashable, so they work as dict keys. Lists do not.
flight_time = {("DEL", "BOM"): 125, ("DEL", "BLR"): 165}
print(flight_time[("DEL", "BLR")]) # 165
# Unpacking names the positions, which reads far better than indexing.
origin, destination = origin_destination
print(f"{origin} -> {destination}") # DEL -> BOM
# Assignment to an element is rejected outright.
try:
origin_destination[0] = "MAA"
except TypeError as exc:
print(exc) # 'tuple' object does not support item assignment# Immutability is shallow: the tuple is frozen, its contents may not be.
settings = (["debug", "verbose"], "production")
settings[0].append("trace") # allowed: the LIST is mutable
print(settings) # (['debug', 'verbose', 'trace'], 'production')
# ...but a tuple containing a list cannot be hashed.
try:
hash(settings)
except TypeError as exc:
print(exc) # unhashable type: 'list'
print(hash(("debug", "production")) is not None) # True: all elements hashableCommon Gotchas
A tuple is not automatically hashable
using `(user_id, tags_list)` as a dict key raises `TypeError: unhashable type: 'list'`. Convert inner sequences to tuples, or inner sets to `frozenset`, before using the tuple as a key.
Building a tuple in a loop is quadratic
`result += (item,)` allocates and copies the entire tuple on every iteration, so n appends cost O(n²). Append to a list and convert once at the end.
A missing comma changes the meaning
`values = (1)` is an integer, and a stray comma in `x = 1,` silently produces the tuple `(1,)`. Both mistakes surface far from where they were written.
Positional fields do not document themselves
`row[3]` forces the reader to count fields. Prefer `namedtuple` or a dataclass once a record has more than two or three parts.