Sub topic 4
Immutability: what is fixed and what is not
This chapter assumes you can read basic Python, know how names refer to objects, and have used lists and append. It builds on the previous chapters, where you created tuples and indexed and sliced them. It explains exactly what "immutable" promises for a tuple and what it leaves open.
What immutable means for a tuple
A tuple is an immutable sequence. After you create it, you cannot add items, remove items, or replace an item with a different one. The tuple has no append, remove, sort or __setitem__ method.
The precise rule is about references. A tuple stores, for each position, a reference to some object. Immutability fixes which objects the tuple points to. It does not freeze the objects themselves.
For an int, a str or another tuple of such values, the distinction does not matter, because those objects cannot change either. It matters when a tuple holds a mutable object such as a list, dict, set or instance of your own class.
t = ([1, 2], 3)
t[0].append(99)
print(t)
try:
t[1] = 4
except TypeError as e:
print(e)The first print shows ([1, 2, 99], 3). The assignment t[1] = 4 tries to change what slot 1 points to, so Python raises TypeError: 'tuple' object does not support item assignment. The call t[0].append(99) never touches the slot. It follows the reference in slot 0 and changes the list that lives there.
Two levels of "frozen"
It helps to separate two questions:
- Can the tuple's own contents be rearranged? No, never.
- Can the value the tuple represents change? Only if one of its items is mutable.
A tuple whose items are all immutable is deeply immutable, so its value can never change. A tuple that holds a mutable item is only shallowly immutable.
| Tuple | Slots can be rebound? | Value can change? |
|---|---|---|
| `(1, "a", 2.5)` | No | No |
| `((1, 2), (3, 4))` | No | No |
| `([1, 2], 3)` | No | Yes, through the list |
| `({"k": 1}, "x")` | No | Yes, through the dict |
Operations that look like changes
Many operations you might expect to modify a tuple instead build a new one. The original is never touched.
t = (1, 2)
original = t
t += (3,)
print(original)
print(t)
print(original is t)This prints (1, 2), then (1, 2, 3), then False. The statement t += (3,) evaluates t + (3,), which creates a new tuple, and then rebinds the name t to it. The name moved. The old tuple stayed the same, and original still refers to it.
The same applies to slicing, concatenation and repetition: t[1:], t + u and t * 2 all produce new tuples. For a list, += calls an in-place method and changes the existing object. For a tuple, no in-place method exists, so Python falls back to creating a new object. This difference can surprise you when two names share one object:
- If two names refer to the same list,
a += [1]changes what both see. - If two names refer to the same tuple,
a += (1,)changes onlya.
That second behaviour is a practical benefit. A tuple you pass to a function or store in a structure cannot be altered behind your back through the tuple itself.
The `+=` trap with a mutable item
Combining augmented assignment with a mutable item inside a tuple gives one of Python's best-known surprises.
t = ([1, 2], 3)
try:
t[0] += [3, 4]
except TypeError as e:
print("error:", e)
print(t)The output is:
error: 'tuple' object does not support item assignment
([1, 2, 3, 4], 3)The statement raises an error and also changes the data. The statement t[0] += [3, 4] runs in three steps:
- Python reads
t[0], which is the list. - It calls the list's in-place add, which extends the list. This succeeds.
- It stores the result back into
t[0]. The tuple refuses, soTypeErroris raised.
By the time the error appears, the list has already grown. The lesson is that an exception does not always mean "nothing happened". If you need to extend a list that lives inside a tuple, call the method directly with t[0].extend([3, 4]). That performs step 2 only and raises no error.
Copying tuples
Because a tuple cannot change, copying it rarely creates a separate object. In CPython (the standard implementation), copy.copy of a tuple returns the same object. The shallow copy still shares any mutable items.
import copy
original = ([1, 2], 3)
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow)
print(deep)
print(shallow is original)This prints ([1, 2, 99], 3), then ([1, 2], 3), then True. The shallow copy is the very same tuple, so it sees the change. The deep copy recursively copies the list into a new object, so it is unaffected. Reach for copy.deepcopy when you need a snapshot that is independent of later changes to nested mutable objects.
Whether a shallow copy returns the same object is an implementation detail of CPython. Do not write code that depends on is returning True or False here. Treat the behaviour as: "a tuple copy shares its items with the original".
Checking whether a tuple is truly fixed
A tuple is hashable only if every item in it is hashable. In practice, the built-in mutable containers (list, dict, set) are unhashable, so hash() on a tuple fails when it contains one. That makes hash() a quick test for "contains no built-in mutable container".
def is_hashable(value):
try:
hash(value)
except TypeError:
return False
return True
print(is_hashable((1, 2)))
print(is_hashable(([1], 2)))
print(is_hashable(((1, 2), "x")))The output is True, False, True.
This test has a limit. Instances of your own classes are hashable by default, using their identity, even though they can be mutated. A tuple holding such an object passes the check but is still not deeply immutable.
class Counter:
def __init__(self):
self.n = 0
c = Counter()
t = (c, "label")
print(is_hashable(t))
c.n += 1
print(t[0].n)This prints True and then 1. The tuple hashes fine, and its content still changed. Hashability tells you the container is safe as a dictionary key under the usual rules. It does not prove that nothing reachable from it can change. The next chapter covers hashing and keys in detail.
Why immutability is useful
- Safe sharing. You can hand the same tuple to several functions or store it in several places without defensive copies, as long as its items are immutable.
- Dictionary keys and set members. Only hashable objects can be keys. Because the contents of an all-immutable tuple never change, its hash never changes, which is the requirement.
- Clear intent. Using a tuple tells readers the collection is a fixed record, such as
(x, y)or(year, month, day), and not a growing list. - Protection against accidental edits. Constants like
DIRECTIONS = ((0, 1), (1, 0), (0, -1), (-1, 0))cannot be reordered or extended by a strayappendelsewhere.
When the data really is a changing sequence, such as results you add to in a loop, use a list. Choosing a tuple for it just forces you to rebuild the tuple on each change.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `t[0] = value` | `TypeError: 'tuple' object does not support item assignment` | Build a new tuple, for example `t = (value,) + t[1:]` |
| Assuming a tuple of lists cannot change | The lists change freely | Use tuples of immutable values, or convert the inner lists to tuples |
| `t[i] += x` where `t[i]` is a list | Error raised after the list was already extended | Call `t[i].extend(x)` instead |
| Using a tuple containing a list as a dict key | `TypeError: unhashable type: 'list'` | Convert the list to a tuple first |
| Expecting `t += (x,)` to update other names bound to `t` | Only the name `t` is rebound | Rebind each name, or use a list |
To change one value in an otherwise fixed tuple, create a replacement. This works and costs one new tuple:
t = (10, 20, 30)
i = 1
t = t[:i] + (99,) + t[i + 1:]
print(t)This prints (10, 99, 30). If you find yourself doing this often, a list is probably the better structure.
Summary of the model
- A tuple's slots are fixed at creation. You cannot add, remove or rebind them.
- The objects in the slots keep their own rules. A mutable object inside a tuple can still change.
- Operations that seem to modify a tuple create a new one, and
+=on a tuple rebinds the name. t[i] += xwith a mutable item changes the item and then raisesTypeError.hash()fails on tuples that contain built-in mutable containers, but it does not catch every case of a mutable object inside.
Exercise
Predict the output of this program, and explain why the list has the value it has even though an exception was raised. t = ([10], "a") try: t[0] += [20] except TypeError: print("failed") print(t)
Show answer
It prints "failed" and then ([10, 20], 'a'). The statement t[0] += [20] first reads the list and extends it in place, which succeeds. Python then tries to store the result back into slot 0 of the tuple, and that raises TypeError because tuples do not support item assignment. The extension already happened, so the list holds [10, 20]. Calling t[0].extend([20]) would avoid the error.
Exercise
Write a function replaceat(t, index, value) that returns a new tuple equal to t but with the item at index replaced by value, and leaves t unchanged. Then say whether replaceat(([1], 2), 1, 5) can still be changed through its first item.
Show answer
def replaceat(t, index, value): return t[:index] + (value,) + t[index + 1:] For example, replaceat((10, 20, 30), 1, 99) returns (10, 99, 30) and the original stays (10, 20, 30). For replace_at(([1], 2), 1, 5), the result is ([1], 5). The new tuple's first slot still refers to the same list as the original, so calling result[0].append(7) changes the list that both tuples share. The replacement only built a new tuple, and the list inside stayed mutable.