Sub topic 1
Mutable and immutable objects
Prerequisites
This chapter assumes you can write basic Python: variables, loops, and functions. You should know the built-in types int, str, and bool, and you should be able to run Python 3 code in a REPL or a script. No other background is needed.
What mutability means
An object is mutable if its contents can change after it is created. An object is immutable if they cannot. In Python, every value is an object. Each object has an identity, a type, and a value. Mutability describes whether the value can change while the identity stays the same.
The four collections in this tutorial split into two groups:
| Type | Mutable? | Notes |
|---|---|---|
| `list` | Yes | Items can be added, removed, and replaced |
| `dict` | Yes | Keys can be added and removed, and values replaced |
| `set` | Yes | Elements can be added and removed |
| `tuple` | No | The set of items it holds is fixed |
Familiar scalar types such as int, str, bool, and float are also immutable.
Identity versus equality
Python gives you two ways to compare objects. The == operator asks whether two objects have equal values. The is operator asks whether two names point to the very same object. The built-in id() returns a number that identifies an object while it exists.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True, the values are equal
print(a is b) # False, they are two separate objects
print(a is c) # True, c is another name for the same object
print(id(a) == id(c)) # TrueAssignment with = never copies an object. It binds a name to an object. This detail matters as soon as the object is mutable.
Changing a mutable object
When you change a mutable object, its identity stays the same. Every name that refers to it sees the change.
scores = [90, 85]
alias = scores
before = id(scores)
scores.append(77)
scores[0] = 95
print(scores) # [95, 85, 77]
print(alias) # [95, 85, 77], the same object seen through another name
print(id(scores) == before) # True, the identity did not changeThe list was modified in place. No new list was created, so alias shows the new contents too.
Immutable objects cannot change in place
An immutable object rejects any attempt to modify it. Operations that look like changes create a new object instead.
point = (3, 4)
try:
point[0] = 1
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
name = "ana"
before = id(name)
name = name + "!"
print(name) # ana!
print(id(name) == before) # False, a new string was createdRebinding a name is different from mutating an object. The line name = name + "!" builds a new string and points name at it. The old string is unchanged.
The same difference shows up with +=. On a list, += extends the existing object. On a tuple, it builds a new one.
items = [1, 2]
alias = items
items += [3]
print(alias) # [1, 2, 3], the same list was extended
pair = (1, 2)
other = pair
pair += (3,)
print(other) # (1, 2), unchanged
print(pair) # (1, 2, 3), a new tupleWhy mutability matters for your choice
Mutability affects three things you will meet in later chapters:
- Shared references. Two names for one mutable object can surprise you. A function that changes a list argument changes the caller's list.
- Hashability. Dict keys and set elements must be hashable, and that rule is tied to immutability. Chapter four covers it.
- Safety. An immutable value is easy to reason about because nobody can alter it behind your back.
A caution about shallow immutability
A tuple being immutable means you cannot replace its items. It does not make the items themselves immutable. If a tuple holds a list, you can still change that list.
t = (1, [2, 3])
t[1].append(4)
print(t) # (1, [2, 3, 4])The tuple still holds the same two objects, the integer 1 and the same list. Only the list's contents changed. Later chapters return to this pitfall.
Summary of the rules
- Lists, dicts, and sets are mutable. Tuples, strings, and numbers are immutable.
- Assignment binds a name to an object and does not copy it.
- Mutating a mutable object keeps its identity and affects every name bound to it.
- Immutability of a container is shallow: it covers the container's own items, not the objects inside them.
Exercise
After running x = [1, 2], y = x, and y += [3], what does x contain, and is x is y true? What changes if x = (1, 2) and y = x and y += (3,)?
Show answer
With lists, x is [1, 2, 3] and x is y is True, because += extends the same list in place. With tuples, x stays (1, 2) and x is y is False, because += builds a new tuple and rebinds y.
Exercise
Given t = ([], []), can you run t[0].append(1)? Can you run t[0] = [1]? Explain both results.
Show answer
t[0].append(1) works, because the tuple holds a mutable list and appending changes that list in place. t[0] = [1] raises a TypeError, because assigning to a tuple item would change which object the tuple holds, and tuples do not allow that.