Sub topic 8
The shared reference trap
This chapter assumes you can create and index lists and dictionaries, write for loops and simple functions, and read nested data with chained indexing. It covers why changing one nested value sometimes changes several, and how to avoid it.
Names point to objects
A Python variable does not hold a value. It holds a reference to an object. Assigning one name to another copies the reference, not the object.
a = [1, 2, 3]
b = a
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # TrueBoth names refer to the same list, so a change made through b shows up through a. The is operator tests whether two names refer to the same object. The == operator tests whether the contents are equal.
Lists and dictionaries are mutable, which means they can be changed in place. Nested data adds a second layer: an outer list can hold several references to one inner list.
The `[[0] * 3] * 2` bug
A common way to build a grid is to multiply a list. It looks right and it is wrong.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]The expression [0] * 3 runs once and produces one inner list. The outer * 2 then repeats a reference to that same list, so bad holds two references to one object. Setting bad[0][0] changes that shared object, and both rows appear to change.
Multiplying the inner list is safe here because 0 is an immutable integer. The problem comes from repeating a mutable object, such as a list or a dictionary.
You can confirm the sharing with is:
bad = [[0] * 3] * 2
print(bad[0] is bad[1]) # TrueThe fix: build each inner object separately
A list comprehension runs its expression once per iteration, so each row is a new list.
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0]]
print(good[0] is good[1]) # FalseThe underscore _ is a conventional name for a loop variable you do not use.
Other places the trap appears
The same bug shows up whenever one mutable object is placed in several spots.
- Default values in
dict.fromkeys().dict.fromkeys(["a", "b"], [])gives every key the same empty list. - Reusing one dictionary in a loop. Appending the same
rowdictionary to a list several times, and changing it between appends, leaves you with many references to one dictionary. - Mutable default arguments. A function defined as
def add(item, bucket=[])creates the list once, and every call that omitsbucketshares it.
Here is the loop case and its fix:
rows = []
row = {"count": 0}
for i in range(3):
row["count"] = i
rows.append(row)
print(rows) # [{'count': 2}, {'count': 2}, {'count': 2}]
rows = []
for i in range(3):
rows.append({"count": i})
print(rows) # [{'count': 0}, {'count': 1}, {'count': 2}]In the first version only one dictionary exists. In the second, each pass through the loop creates a new one.
And here is the default-argument case:
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add(1)) # [1]
print(add(2)) # [2]Using None as the default and creating the list inside the function gives each call its own list.
Sharing is sometimes what you want
Shared references are not always a mistake. If two parts of a program should see the same configuration object, sharing it is the point. The trap is sharing by accident. When you build a structure, ask whether each inner list or dictionary should be its own object.
Quick checklist
| Situation | Safe? | Why |
|---|---|---|
| `[0] * 3` | Yes | The items are immutable integers. |
| `[[0] * 3] * 2` | No | One inner list is repeated. |
| `[[0] * 3 for _ in range(2)]` | Yes | A new inner list is built each time. |
| `dict.fromkeys(keys, [])` | No | Every key gets the same list. |
| `{k: [] for k in keys}` | Yes | A new list is built for each key. |
Exercise
The code grid = [[None] * 2] * 3 is followed by grid[2][1] = "x". What does print(grid) show, and how would you change the first line so only the last row is affected?
Show answer
It prints [[None, 'x'], [None, 'x'], [None, 'x']], because all three rows are the same list. Build the grid with a comprehension: grid = [[None] * 2 for _ in range(3)]. Then the assignment changes only the last row, giving [[None, None], [None, None], [None, 'x']].
Exercise
You write groups = dict.fromkeys(["a", "b"], []) and then groups["a"].append(1). What does groups["b"] contain? Write a version that avoids the problem.
Show answer
groups["b"] is [1], because both keys refer to the same list. Use a dictionary comprehension: groups = {key: [] for key in ["a", "b"]}. Each key then gets its own list.