Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Data types & structuresSeniorOccasionalTroubleshooting

A tuple is immutable, so why does `t = ([1, 2], 3); t[0].append(4)` succeed without error?

Answer

Tuple immutability only protects the tuple's own bindings: which objects sit at each index can never change after creation. It says nothing about the mutability of the objects those slots reference. If a slot holds a mutable object like a list, that object can still be mutated in place through its own methods; only reassigning the slot itself (`t[0] = something`) would fail with a TypeError. This also means a tuple's hashability depends on whether every element it holds is itself hashable, not on mutability directly: `([1, 2], 3)` is unhashable specifically because `list` is unhashable, so it cannot be used as a dict key or set member, while a tuple holding only hashable elements remains hashable even if one of those elements is a custom mutable object that happens to define `__hash__`.

Strong answer includes

  • immutability protects slot bindings, not referenced object contents
  • in-place mutation of a mutable element still works
  • tuple hashability depends on every element being hashable, not on mutability directly

Practical example

Python example
t[0].append(4)

mutates the list stored at index 0 in place and succeeds, but

Python example
t[0] = [9]

raises `TypeError: 'tuple' object does not support item assignment` .

#tuples#mutability#gotchas

Sources

Data modelPython Software Foundation · Dunder methods, object identity, attribute lookup and the descriptor and context manager protocols