Sub topic 2
Mutability and aliasing
This chapter covers what happens when two names refer to the same object, and why the answer depends on whether that object can change. It assumes you know basic Python syntax (functions, classes, lists, dictionaries). It also assumes you have read the previous chapter, where a variable is a name bound to an object, and that you know the code runs on the CPython interpreter.
Mutable and immutable objects
An object is mutable if its contents can change after it is created, without changing its identity. An object is immutable if its contents are fixed once it exists. Identity is the value returned by id() and compared by is.
| Type | Mutable? | Notes |
|---|---|---|
| `int`, `float`, `bool`, `complex` | No | Operations produce new objects |
| `str`, `bytes` | No | Slicing and concatenation produce new objects |
| `tuple`, `frozenset` | No | A tuple may still contain mutable objects |
| `list`, `dict`, `set`, `bytearray` | Yes | Methods such as `append` change the object in place |
| Instances of user-defined classes | Usually yes | Attributes can be reassigned unless you prevent it |
Mutability is a property of the object, not of the name. A name can always be rebound to a different object. Only a mutable object can be changed through the name.
Aliasing: two names, one object
An alias is a second name bound to an object that already has a name. Assignment never copies. It binds a name to the object on the right-hand side.
a = [1]
b = a
b.append(2)
print(a) # [1, 2]
print(a is b) # True
c = list(a)
print(a is c) # Falseb = a creates no new list. The append call changes the one list that both a and b refer to, so the change shows through either name. list(a) builds a new list with the same elements, so c is a separate object.
Aliasing with immutable objects is harmless, because nobody can change the shared object. Two names bound to the same string never interfere with each other. Aliasing bugs only appear with mutable objects.
Checking identity and equality
== asks whether two objects have equal values. is asks whether two names refer to the very same object. After c = list(a), a == c is True and a is c is False. Use is for identity checks such as x is None. Do not use it to compare values, because whether two equal immutable objects are the same object is an implementation detail. A later chapter on interning covers this.
Aliasing through function arguments
Python passes arguments by binding the parameter name to the argument object. The parameter is therefore an alias of whatever the caller passed. What the function does next decides whether the caller sees a change.
def add_item(items):
items.append("x") # mutates the shared object
def rebind(items):
items = items + ["y"] # builds a new list; only the local name changes
data = []
add_item(data)
rebind(data)
print(data) # ['x']add_item changes the object the caller also holds. rebind creates a new list and binds the local name items to it, which leaves the caller's list alone. The rule is that mutation is visible to every alias, and rebinding is visible only to the name that was rebound.
Mutable default arguments
A default value is evaluated once, when the def statement runs, not on each call. A mutable default is therefore a single object that all calls share.
def append_to(value, bucket=[]):
bucket.append(value)
return bucket
print(append_to(1)) # [1]
print(append_to(2)) # [1, 2] (the same list as the first call)The usual fix is to use None as a sentinel and create the list inside the function.
def append_to(value, bucket=None):
if bucket is None:
bucket = []
bucket.append(value)
return bucket
print(append_to(1)) # [1]
print(append_to(2)) # [2]Augmented assignment can mutate or rebind
The statement x += y calls x.__iadd__(y) if the type defines it. Otherwise it falls back to x = x + y. Mutable types such as list define __iadd__ and change the object in place. Immutable types cannot, so += creates a new object and rebinds the name.
x = [1]
y = x
x += [2] # in place: y sees the change
print(y) # [1, 2]
x = x + [3] # new list: y is unaffected
print(y) # [1, 2]
print(x) # [1, 2, 3]
m = (1,)
n = m
m += (2,) # tuples are immutable, so m is rebound to a new tuple
print(n) # (1,)
print(m) # (1, 2)The two list forms look equivalent but behave differently when aliases exist. If you want a new list and must not disturb other holders of the old one, write x = x + [3] or x = [*x, 3].
Immutable containers holding mutable objects
A tuple cannot change which objects it refers to, but it does not freeze those objects. A tuple holding a list is immutable only in the sense that its slots are fixed.
t = (1, [2])
try:
t[1] += [3]
except TypeError as error:
print(error) # 'tuple' object does not support item assignment
print(t) # (1, [2, 3])This is a well-known edge case. The statement t[1] += [3] runs in two steps. First the list's __iadd__ extends the list in place, which succeeds. Then Python tries to store the result back into slot 1 of the tuple, which raises TypeError. The error is reported, but the list has already changed. To avoid this, call t[1].extend([3]), which has no store step.
The same distinction affects hashing. A hashable object must have a hash that never changes while it lives in a dictionary or set. Mutable built-in containers are therefore unhashable, and a tuple is hashable only if everything inside it is.
try:
{[1]: "x"}
except TypeError as error:
print(error) # unhashable type: 'list'
try:
hash((1, [2]))
except TypeError as error:
print(error) # unhashable type: 'list'Copying: shallow and deep
When you need independent data instead of an alias, you must copy. A shallow copy creates a new container but fills it with references to the same elements. A deep copy copies the container and, recursively, the objects inside it.
Ways to make a shallow copy of a list include list(a), a.copy(), and a[:]. For dictionaries, use dict(d) or d.copy(). For general objects, use copy.copy. Deep copies come from copy.deepcopy.
import copy
original = [[1], [2]]
shallow = original.copy()
shallow[0].append(9)
print(original) # [[1, 9], [2]]
print(original[0] is shallow[0]) # True: the inner list is shared
deep = copy.deepcopy(original)
deep[1].append(8)
print(original) # [[1, 9], [2]]
print(deep) # [[1, 9], [2, 8]]The shallow copy protects the outer list. Adding or removing elements in shallow does not affect original. Changes to the shared inner lists still show through both.
Repetition creates aliases
The expression [x] * n repeats a reference to x. It does not copy x. With an immutable element this is fine. With a mutable element, all slots refer to one object.
grid = [[0] * 2] * 3
grid[0][0] = 1
print(grid) # [[1, 0], [1, 0], [1, 0]]
good = [[0] * 2 for _ in range(3)]
good[0][0] = 1
print(good) # [[1, 0], [0, 0], [0, 0]]The comprehension evaluates [0] * 2 once per row, so each row is a different list.
Aliasing in classes
Class attributes are shared across instances. If a class attribute is a mutable object, every instance sees the same object until an instance binds its own.
class Team:
members = [] # one list, owned by the class
def add(self, name):
self.members.append(name)
a, b = Team(), Team()
a.add("Ana")
print(b.members) # ['Ana']
class FixedTeam:
def __init__(self):
self.members = [] # one list per instance
c, d = FixedTeam(), FixedTeam()
c.members.append("Ana")
print(d.members) # []Create per-instance mutable state in __init__. The same care applies to dataclasses, where a mutable default must use field(default_factory=list).
Why this matters for memory
Aliasing is the reason an object's lifetime is not tied to the name you used to create it. The list in the first example stays alive as long as any of a or b refers to it. Deleting a removes only the name. The object is freed when the last reference goes away, which is the subject of the next chapter. It also means a long-lived alias, such as a global cache or a default argument, can keep a large object in memory for the life of the program.
Exercise
What do the two print calls show, and why? def grow(values, extra): values += extra return values first = [1, 2] second = grow(first, [3]) print(first) print(second is first)
Show answer
The first call prints [1, 2, 3] and the second prints True. The += on a list calls __iadd__, which extends the list in place, so the object the caller passed is mutated. The function then returns that same object, so second is another name for the list that first refers to. If the body used values = values + extra, a new list would be built and first would stay [1, 2].
Exercise
A programmer writes rows = [{}] * 3 and then runs rows[0]["id"] = 7. What does rows contain afterwards, and how should the list be built instead?
Show answer
It contains [{'id': 7}, {'id': 7}, {'id': 7}], because the repetition places three references to one dictionary in the list, so all three slots are the same object. Build independent dictionaries with rows = [{} for _ in range(3)], which evaluates {} once per element.