Q&A-4What does tuple immutability guarantee, and what does it not guarantee?
Answer
Short answer
Tuple immutability guarantees one thing: the tuple's slot array is fixed. Once built, a tuple holds the same references, in the same order, at the same length, for its whole life. It does not guarantee that the objects those references point at are immutable. A tuple is an immutable sequence of references, not a deep freeze. t[0] = x always raises; t[0].append(x) succeeds whenever t[0] is a list.
The mechanism, traced
>>> t = ([1, 2], "name")
>>> t[0].append(3)
>>> t
([1, 2, 3], 'name')
>>> t[0] = [9]
TypeError: 'tuple' object does not support item assignmentWalk it the way CPython does. t is a PyTupleObject: a header plus a fixed array of two PyObject * slots. t[0] reads slot 0 and returns the list object: no copy, no wrapper. .append(3) calls list.append on that object, mutating the list's own internal array. The tuple is untouched: slot 0 still holds the same pointer, slot 1 still holds the same string, len(t) is still 2. The second statement is different: t[0] = ... compiles to STORE_SUBSCR, and tuple has no tp_ass_subscript slot, so CPython raises TypeError before evaluating the right-hand side.
The trap that catches people in review:
>>> t = ([1],)
>>> t[0] += [2]
TypeError: 'tuple' object does not support item assignment
>>> t
([1, 2],)t[0] += [2] is t[0] = t[0].__iadd__([2]). list.__iadd__ mutates in place and returns the list, so the list is already [1, 2] when the store back into slot 0 fails. The exception is real and the mutation is real; code that reads "the tuple didn't change" as "nothing changed" is wrong here.
The boundary that matters: hashability
A tuple's hash is derived from its elements, so a tuple is hashable only if every element is:
>>> hash((1, 2))
-3550055125485641917
>>> hash(([1], 2))
TypeError: unhashable type: 'list'Two details matter. The check happens at hash() time, not construction time: ([1], 2) is a perfectly valid tuple that simply cannot be hashed. And CPython does not cache a tuple's hash: PyTupleObject has no hash field, so hash(t) recomputes over all n elements on every call, O(n) with n __hash__ calls. str caches its hash in PyASCIIObject.hash, which is why a long string key is cheap on the second lookup and a long tuple key is not: a 1000-element tuple used as a dict key pays 1000 element hashes per lookup. A tuple of ints hashes identically across runs; a tuple of strings does not, because string hashing is salted by PYTHONHASHSEED.
Hashability is also not stability. An object can define __hash__ and still mutate:
class P:
def __init__(self): self.x = 1
def __hash__(self): return hash(self.x)
d = {(P(),): "v"} # hash is stable, p.x is notThe tuple is immutable, the key's hash is well-defined, and the dict entry is still unreachable once p.x changes. Immutability of the container and value-stability of the contents are separate properties.
What immutability buys
- Fixed shape and length: unpacking is a single
UNPACK_SEQUENCEand cannot fail on arity drift.lat, lon = (51.5, -0.12). - Stable reference identity: the tuple never silently points at different objects, so it is safe to share across threads (including free-threaded 3.13t builds) without a lock on the tuple itself.
- Cheap copies:
copy.copy(t) is tisTrue.copyregisters tuples as immutable and returns the same object.copy.deepcopyreturns the original too when every element is atomic. - Compile-time folding: a literal tuple of constants is built once by the compiler and loaded with
LOAD_CONST; the empty tuple()is a singleton in CPython. - No growth path: a tuple allocates exactly n pointer slots (8 bytes each on a 64-bit CPython 3.12 build). A list carries a separate capacity field and over-allocates,
list_resizegrows tonewsize + (newsize >> 3) + (newsize < 9 ? 3 : 6), so a list is never smaller than the tuple holding the same items.
What it does not buy
- No deep immutability: nested lists, dicts and sets stay mutable.
- No thread safety for the contents: the slot array is safe to read concurrently, the list inside it is not.
- No hashability guarantee, and no protection against a mutable-but-hashable element.
- No field semantics:
t[0]andt[1]are positional. Usenamedtuple/NamedTuplefor named access, or@dataclass(frozen=True)when you want validation and aFrozenInstanceError(anAttributeErrorsubclass) on assignment: neither deep-freezes fields. - No in-place growth:
t += (4,)rebinds the name to a new tuple;t2 = t; t += (4,); t is t2isFalse.
Tradeoffs
| Need | Choice | Why |
|---|---|---|
| Fixed-shape record, immutable fields | tuple | fewest slots, hashable, copy-free |
| Same, with named fields | namedtuple / NamedTuple | tuple layout plus _replace/_asdict |
| Validation or behavior | @dataclass(frozen=True) | FrozenInstanceError on assignment; still shallow |
| Unordered immutable set | frozenset | hashable, no ordering assumption |
| True deep immutability | convert nested data yourself | Python has no built-in deep freeze |
If any field is a list, dict or set, the tuple is the wrong dict key or set member regardless of its own immutability: normalize the nested data first.
Falsifiable summary
Claim: a tuple's sequence of references cannot be replaced, but a referenced object may itself be mutable. The t[0].append(3) / t[0] = [9] trace confirms both halves, and t[0] += [2] shows both can happen in one statement. The common wrong answer ("tuples are immutable, so their contents can't change") fails on the first line of the trace and again on hash(([1], 2)).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.