Sub topic 3
The Shared Reference Trap
Assume you know basic lists, dictionaries, loops, and functions. Nested structures add levels, but they also add references: names point to objects rather than containing independent copies of those objects.
The shared reference trap
List multiplication repeats references to the same inner list:
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
good = [[0] * 3 for _ in range(2)]
good[0][0] = 1
print(good) # [[1, 0, 0], [0, 0, 0]]The comprehension creates a new inner list for every row.
Shallow copies versus deep copies
A shallow copy duplicates only the outer container. Its nested objects remain shared. A deep copy duplicates every nested level.
| Operation | Nested lists or dictionaries |
|---|---|
| `copy.copy(value)` | Shares inner objects |
| `copy.deepcopy(value)` | Copies inner objects too |
import copy
original = {"tags": ["python", "data"]}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original["tags"].append("json")
print(shallow["tags"]) # ['python', 'data', 'json']
print(deep["tags"]) # ['python', 'data']Nested data and JSON
The json module converts nested Python dictionaries and lists to JSON text and back. JSON supports strings, numbers, booleans, None, lists, and dictionaries with string keys.
import json
data = {"user": {"name": "Ana", "roles": ["admin", "dev"]}}
text = json.dumps(data, indent=2)
restored = json.loads(text)
print(restored["user"]["roles"][0]) # adminWalking data of unknown depth with recursion
Recursion is when a function calls itself. It works well when dictionaries and lists can contain more dictionaries and lists at any depth.
def walk(value, path=()):
if isinstance(value, dict):
for key, child in value.items():
yield from walk(child, path + (key,))
elif isinstance(value, list):
for index, child in enumerate(value):
yield from walk(child, path + (index,))
else:
yield path, valueKnowing when to stop nesting
Deep nesting can make data difficult to validate and read. Use a class or dataclass when the data has named concepts, rules, or behavior.
Exercise
Why does changing bad[0][0] also change bad[1][0]?
Show answer
Both rows reference the same inner list, so one mutation is visible through both references.