Sub topic 8
The shared reference trap
This chapter explains why changing one row of a nested list can change several rows at once. It covers the cause, the usual places the bug shows up, how to detect it, and how to fix it. It assumes you can index lists and dictionaries, write for loops and simple functions, and know the difference between a mutable and an immutable type. The next chapter covers shallow and deep copies, so this chapter only previews them.
Names point to objects
A Python variable is a name bound to an object. It does not hold the object's contents. An assignment such as b = a binds a second name to the same object and creates no new data.
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
print(a is b) # TrueThe is operator asks whether two names point to the very same object. The == operator asks whether two objects have equal contents. Two separate lists can be equal without being identical.
x = [1, 2]
y = [1, 2]
print(x == y) # True
print(x is y) # FalseMutating an object through one name is visible through every name bound to it. Rebinding a name only moves that one name, and the other names are unaffected.
a = [1, 2, 3]
b = a
b = b + [4] # builds a new list and rebinds b
print(a) # [1, 2, 3]
print(b) # [1, 2, 3, 4]
print(a is b) # FalseNested structures follow the same rule. A list does not contain other lists. It contains references to them, and several slots can reference the same inner list.
The classic bug: multiplying a nested list
The expression [0] * 3 builds [0, 0, 0]. The expression [...] * 2 repeats the references in the outer list. It does not copy the objects they point to.
bad = [[0] * 3] * 2
print(bad[0] is bad[1]) # True
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]Only one inner list exists. The outer list has two slots, and both point to it. Writing through bad[0] changes the object that bad[1] also reaches.
The inner [0] * 3 is not the problem. It repeats the integer 0, and integers are immutable, so no operation can change that shared 0 in place. The statement row[0] = 1 rebinds one slot of row and leaves the integer alone. Sharing is harmless for immutable objects and dangerous for mutable ones such as lists, dicts, and sets.
Replacing a whole row does not trigger the bug, because assignment to a slot rebinds only that slot.
bad = [[0] * 3] * 2
bad[0] = [9, 9, 9] # rebinds slot 0 only
print(bad) # [[9, 9, 9], [0, 0, 0]]This behavior is why the bug is confusing. Some operations on the same structure behave correctly, and others do not.
The fix: build a new object per slot
A list comprehension evaluates its expression once for each iteration. The expression [0] * 3 therefore runs again each time and produces a fresh inner list.
good = [[0] * 3 for _ in range(2)]
print(good[0] is good[1]) # False
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0]]The general rule is that any mutable object that must be independent has to be created inside the loop or comprehension. An equivalent explicit loop works the same way.
good = []
for _ in range(2):
good.append([0] * 3) # a new list on every passOther places the trap appears
The cause is always the same: one mutable object is created once and then placed in several locations.
Repeating other mutable values
All of these forms share one object across slots:
lists = [[]] * 3
dicts = [{}] * 3
lists[0].append("x")
dicts[1]["k"] = "v"
print(lists) # [['x'], ['x'], ['x']]
print(dicts) # [{'k': 'v'}, {'k': 'v'}, {'k': 'v'}]The fixes are [[] for _ in range(3)] and [{} for _ in range(3)].
dict.fromkeys with a mutable default
The second argument of dict.fromkeys() is evaluated once, and every key gets a reference to that one value.
keys = ["a", "b"]
shared = dict.fromkeys(keys, [])
shared["a"].append(1)
print(shared) # {'a': [1], 'b': [1]}
separate = {key: [] for key in keys}
separate["a"].append(1)
print(separate) # {'a': [1], 'b': []}dict.fromkeys(keys, 0) is safe because 0 is immutable. Only mutable values cause trouble.
Appending the same list inside a loop
A common version of the bug builds rows by reusing one working list.
row = []
grid = []
for i in range(3):
row.append(i)
grid.append(row)
print(grid) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]The code appends the same row object three times. Creating the list inside the loop fixes it:
grid = []
for i in range(3):
row = [] # a new list each pass
for j in range(i + 1):
row.append(j)
grid.append(row)
print(grid) # [[0], [0, 1], [0, 1, 2]]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 shared by every call that omits the argument.
def add_tag(tag, tags=[]):
tags.append(tag)
return tags
print(add_tag("a")) # ['a']
print(add_tag("b")) # ['a', 'b']The usual fix uses None as a marker and creates the list inside the function:
def add_tag(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(add_tag("a")) # ['a']
print(add_tag("b")) # ['b']Reusing a template dictionary
A record template placed in several spots gives the same aliasing problem with dictionaries:
template = {"hp": 10, "items": []}
players = {name: template for name in ["ana", "ben"]}
players["ana"]["items"].append("sword")
print(players["ben"]["items"]) # ['sword']Building the dictionary inside the comprehension gives each player their own record:
players = {name: {"hp": 10, "items": []} for name in ["ana", "ben"]}
players["ana"]["items"].append("sword")
print(players["ben"]["items"]) # []Functions mutate what they receive
Python passes references into functions. If a function changes a nested object it received, the caller sees the change. This is often intended, but it surprises people who expect the function to work on a private copy.
def add_grade(student, grade):
student["grades"].append(grade)
ana = {"name": "Ana", "grades": [90, 85]}
add_grade(ana, 95)
print(ana["grades"]) # [90, 85, 95]If a function should leave its input untouched, it has to build and return a new structure. The next chapter shows how to copy the input first.
Operations that look like copies
Several operations create a new outer container but keep references to the same inner objects. The table shows which ones duplicate what.
| Operation | New outer container? | Inner objects shared? |
|---|---|---|
| `b = a` | No, same object | Yes, everything |
| `a * n` | Yes | Yes, repeated `n` times |
| `a[:]`, `list(a)`, `a.copy()` | Yes | Yes |
| `dict(d)`, `d.copy()` | Yes | Yes |
| `[[0] * 3 for _ in range(n)]` | Yes | No, each row is new |
| `copy.deepcopy(a)` | Yes | No, every level is duplicated |
A copy that duplicates only the top level is called a shallow copy. It protects you from changes to the outer container, such as adding or removing items. It does not protect you from changes inside the nested objects.
original = [[1, 2], [3, 4]]
clone = original[:]
clone.append([5, 6]) # affects only clone
clone[0].append(99) # affects both, because row 0 is shared
print(original) # [[1, 2, 99], [3, 4]]
print(clone) # [[1, 2, 99], [3, 4], [5, 6]]Full copies are covered in the next chapter.
Detecting sharing
When a nested structure behaves strangely, check whether its inner objects are identical. The built-in id() returns a number that is unique to an object during its lifetime, so counting distinct ids tells you how many separate objects exist.
def has_shared_rows(grid):
return len({id(row) for row in grid}) < len(grid)
bad = [[0] * 3] * 2
good = [[0] * 3 for _ in range(2)]
print(has_shared_rows(bad)) # True
print(has_shared_rows(good)) # FalseFor a single pair you can write a is b. Also keep these edge cases in mind:
- Small integers and short strings may be shared by the interpreter. This is invisible and harmless because they are immutable. Do not rely on
isto compare numbers or strings. Use==. - An empty tuple and a tuple of immutable items may be reused too. Sharing becomes a problem only when the shared object is mutable.
- A tuple that contains a list is immutable in its slots but not in its contents. The list inside it can still be mutated, and every reference to the tuple sees the change.
t = ([1], [2])
alias = t
t[0].append("x")
print(alias) # (['x'], [2])Deliberate sharing
Sharing is not always a bug. Sometimes you want two parts of a program to see the same data, such as a cache, a configuration object, or a registry referenced from several records. The rule is to make the sharing a decision, not a side effect of * or a default argument. If you share an object on purpose, name it clearly and add a comment, so the next reader does not treat it as a mistake and "fix" it.
shared_settings = {"theme": "dark"} # intentionally shared
users = [
{"name": "Ana", "settings": shared_settings},
{"name": "Ben", "settings": shared_settings},
]
shared_settings["theme"] = "light"
print(users[1]["settings"]["theme"]) # lightChecklist for avoiding the trap
- Never use
*to repeat a list that contains mutable objects. - Create mutable objects inside the loop or comprehension that fills the structure.
- Never use a mutable object as a default argument. Use
Noneand build the object in the body. - Pass a mutable value to
dict.fromkeys()only if you want all keys to share it. - Treat
copy(),[:], andlist()as one-level copies. - When a bug appears only after a write, test the inner objects with
isorid().
Exercise
What does this code print, and why? Then rewrite the first line so the output is [[1], [], []].
rows = [[] for _ in range(3)] 1
table = [[]] 3
table[0].append(1)
print(table)
Show answer
It prints [[1], [1], [1]]. The expression [[]] * 3 builds one empty list and repeats a reference to it three times, so table[0], table[1], and table[2] are the same object. The line rows = ... is unrelated to table. The fix is table = [[] for _ in range(3)], which creates a new list on every iteration, so only the first row receives the 1.
Exercise
This function is meant to return a new list each time it is called with no second argument. Explain why the second call prints [1, 2], and fix the function.
def collect(item, bucket=[]):
bucket.append(item)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [1, 2]
Show answer
The default [] is created once, when def runs, and every call without a bucket argument reuses that one list. Fix it with a None default:
def collect(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
Now each call without a bucket argument gets a new list, so the second call prints [2].
Exercise
Given original = {"tags": ["a"], "n": 1} and clone = original.copy(), you run clone["n"] = 2 and clone["tags"].append("b"). What are original["n"] and original["tags"] afterward?
Show answer
original["n"] is still 1, and original["tags"] is ['a', 'b']. The assignment clone["n"] = 2 rebinds a slot in the clone's own top-level dictionary, which the original does not share. The append mutates the list that both dictionaries reference, because copy() is a shallow copy.