Sub topic 9
Pitfalls: shared references, mutable defaults, and mutable items inside tuples
This chapter assumes you know Python basics (variables, loops, functions) and the difference between mutable and immutable objects from earlier in the tutorial. Three bugs account for most surprises with collections: two names that share one object, a default argument that persists between calls, and a mutable object hidden inside a tuple. Each follows from one rule: a variable holds a reference to an object, not a copy of it.
Shared references
Assignment never copies a list, dict, or set. It binds a second name to the same object.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # True, both names point to one objectis tests identity (same object). == tests equality (same contents). Two separate lists can be equal without being identical.
To get an independent top-level copy, use list(a), a.copy(), or a[:]. For dicts and sets, use .copy() or the constructors dict(d) and set(s).
The shallow copy trap
A copy made this way is shallow. It copies the outer container but reuses the inner objects.
grid = [[0, 0], [0, 0]]
copy = grid.copy()
copy[0].append(9)
print(grid) # [[0, 0, 9], [0, 0]]
bad = [[0] * 2] * 2 # two references to ONE inner list
bad[0][0] = 1
print(bad) # [[1, 0], [1, 0]]
good = [[0] * 2 for _ in range(2)] # a new inner list each time
good[0][0] = 1
print(good) # [[1, 0], [0, 0]]For a fully independent nested structure, use copy.deepcopy.
import copy
grid = [[0, 0], [0, 0]]
deep = copy.deepcopy(grid)
deep[0].append(9)
print(grid) # [[0, 0], [0, 0]]Mutable default arguments
Python evaluates a default value once, when the def statement runs. It does not re-evaluate it on each call. A mutable default is therefore one object shared by every call that omits the argument.
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2], because the default list is shared between callsThe standard fix is to use None as a sentinel and create the list inside the function.
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [2]Use is None rather than if not bucket. An empty list passed in by the caller is falsy, and the shortcut would silently replace the caller's list with a new one.
Mutable items inside tuples
A tuple is immutable, but only shallowly. It fixes which objects it holds. It does not freeze those objects.
t = (1, [2, 3])
t[1].append(4)
print(t) # (1, [2, 3, 4])Augmented assignment on such an item shows an odd result. += first mutates the list, then tries to rebind the tuple slot, which fails.
t = (1, [2, 3])
try:
t[1] += [4]
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
print(t) # (1, [2, 3, 4]), the list changed before the errorThis also affects hashing. A tuple is hashable only if all its items are. A tuple that contains a list cannot be a dict key.
try:
{(1, [2, 3]): "value"}
except TypeError as e:
print(e) # unhashable type: 'list'Quick reference
| Pitfall | Symptom | Fix |
|---|---|---|
| `b = a` on a mutable object | Change through `b` shows up in `a` | `a.copy()` or `list(a)` |
| Shallow copy of nested data | Inner lists still shared | `copy.deepcopy` or build with a comprehension |
| `[[0] * n] * m` | Every row changes together | `[[0] * n for _ in range(m)]` |
| Mutable default argument | Data persists between calls | Default to `None`, create inside |
| List inside a tuple | Tuple "changes" or cannot be hashed | Use immutable items, such as nested tuples |
Exercises
Exercise
What does this code print, and how do you change make_row so each call returns an independent list?
def makerow(value, row=[]):
row.append(value)
return row
print(makerow("a"))
print(make_row("b"))
Show answer
It prints ['a'] and then ['a', 'b'], because the default list is created once and shared by both calls. Change the signature to def make_row(value, row=None):, and add if row is None: row = [] as the first line of the body. Then the output is ['a'] and ['b'].
Exercise
Given t = ([1], [2]), can you run t[0].append(5)? Can you run t[0] = [5]? Explain the difference.
Show answer
t[0].append(5) works, because it mutates the list object that the tuple refers to and does not change which object is in slot 0. t[0] = [5] raises TypeError, because it tries to rebind slot 0 of the tuple, and tuples do not allow item assignment.