Sub topic 4
Immutability: what is fixed and what is not
This chapter assumes you know basic Python syntax, variables, lists and indexing, and how to create a tuple. It covers what "immutable" promises for a tuple and where that promise stops.
What immutable means
A tuple is immutable. Once it exists, you cannot add, remove or replace its items. Methods like append and remove do not exist on tuples, and item assignment fails.
More precisely, a tuple stores references to objects. Immutability fixes which objects the tuple refers to, and in what order. It says nothing about whether those objects can change.
point = (3, 4)
try:
point[0] = 10
except TypeError as e:
print(e)
print(point)The assignment raises TypeError, and point is unchanged.
Mutable objects inside a tuple
If an item is itself mutable, such as a list, that object can still change. The tuple keeps pointing at the same list. The list's contents are a separate matter.
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 would rebind a slot in the tuple, so it raises TypeError.
The += surprise
Augmented assignment on a tuple item shows both effects at once. Consider this code.
t = ([1, 2], 3)
try:
t[0] += [4]
except TypeError as e:
print(e)
print(t)Python first runs t[0].__iadd__([4]), which extends the list in place. It then tries to store the result back into t[0], and that step fails. The output shows the error, yet t is now ([1, 2, 4], 3). The operation partly succeeded.
Rebinding versus mutating
A name that points to a tuple can be rebound to a new tuple. That does not change the original tuple.
a = (1, 2)
b = a
a = a + (3,)
print(a)
print(b)a + (3,) builds a new tuple, so a is (1, 2, 3) while b is still (1, 2). Every "change" to a tuple is really the creation of a new one. Repeated concatenation in a loop copies the items each time, so for long sequences build a list and convert it with tuple(...) at the end.
What you gain
- Safety. Code that receives a tuple cannot reorder or resize it, so you can pass one around without defensive copies of its structure.
- Intent. A tuple signals a fixed group of values, such as a coordinate or a database row.
- Hashability. A tuple whose items are all hashable can be a dictionary key. The next chapter covers this.
Checking for deep immutability
Python has no built-in test for "fully immutable". Attempting to hash the tuple is a practical check, because hashing fails if any item is unhashable.
def is_hashable(obj):
try:
hash(obj)
except TypeError:
return False
return True
print(is_hashable((1, 2, 3)))
print(is_hashable(([1, 2], 3)))This prints True, then False. It is a good signal but not a proof. A custom class can be hashable and still mutable.
Exercise
Given t = ([10, 20], "x"), which of these succeed: t[0].append(30), t[1] = "y", t[0] = [1]? What does t look like afterward?
Show answer
Only t[0].append(30) succeeds, because it mutates the list the tuple refers to. The other two try to rebind a slot in the tuple, so each raises TypeError. Afterward t is ([10, 20, 30], "x").
Exercise
After a = (1, 2) and b = a, you run a += (3,). What are a and b, and why is b unaffected?
Show answer
a is (1, 2, 3) and b is (1, 2). Tuples have no in-place add, so += builds a new tuple and rebinds the name a. The original tuple, which b still refers to, is never modified.