Sub topic 9
Shallow copies versus deep copies
This chapter assumes you can index lists and dictionaries, loop over them, and know that two names can refer to the same object. The previous chapter showed how [[0] * 3] * 2 repeats one inner list. Copying has the same cause: a copy of a container does not always copy what is inside it.
Assignment is not copying
Writing b = a creates no new object. Both names point at the same one, so a change through either name shows up in both.
a = {"tags": ["x"]}
b = a
b["tags"].append("y")
print(a) # {'tags': ['x', 'y']}
print(a is b) # TrueTo get an independent object, you have to copy it explicitly.
What a shallow copy does
A shallow copy makes a new outer container. It fills that container with references to the same inner objects the original holds. Common ways to make one are list.copy(), dict.copy(), slicing with items[:], list(items), dict(d), and copy.copy().
import copy
original = {"name": "Ana", "tags": ["a", "b"]}
shallow = copy.copy(original)
shallow["name"] = "Ben" # replaces a value in the copy only
shallow["tags"].append("c") # mutates the list both dicts share
print(original) # {'name': 'Ana', 'tags': ['a', 'b', 'c']}
print(shallow) # {'name': 'Ben', 'tags': ['a', 'b', 'c']}
print(original["tags"] is shallow["tags"]) # TrueTwo different things happened here:
- Assigning a new value to a key of the copy rebinds that key in the copy. The original is untouched.
- Mutating a shared inner object, as
appenddoes, changes it for every container that references it.
What a deep copy does
copy.deepcopy() copies the outer container and then copies everything inside it, level by level. The result shares no mutable objects with the original.
import copy
original = {"tags": ["a", "b"]}
shallow = original.copy()
deep = copy.deepcopy(original)
original["tags"].append("c")
print(shallow["tags"]) # ['a', 'b', 'c']
print(deep["tags"]) # ['a', 'b']Deep copy also handles objects that refer to themselves or appear twice in the structure. It keeps a record of what it has already copied, so a shared inner object stays shared inside the copy, and a cycle does not cause infinite recursion.
Lists of dictionaries
The same rule applies to lists. Copying a list of dictionaries leaves the dictionaries shared.
import copy
rows = [{"id": 1, "score": 10}, {"id": 2, "score": 20}]
shallow_rows = rows.copy()
shallow_rows[0]["score"] = 99
print(rows[0]["score"]) # 99, because the dict is shared
safe_rows = copy.deepcopy(rows)
safe_rows[1]["score"] = 0
print(rows[1]["score"]) # 20A common bug follows from this. A function receives a list of dictionaries, copies the list with .copy() to "avoid changing the caller's data", and then edits the dictionaries. The caller's data still changes.
Choosing between them
| Situation | Use |
|---|---|
| All values are immutable (numbers, strings, tuples of those) | A shallow copy is enough |
| You only add or remove items at the top level | A shallow copy is enough |
| You will change anything inside inner lists or dictionaries | `copy.deepcopy()` |
| You need a snapshot to compare against later | `copy.deepcopy()` |
A shallow copy is faster and uses less memory. Deep copy cost grows with the size of the whole structure. Do not use it by habit on large data when you only need a top-level copy.
Common errors
- Assuming
.copy()on a nested structure is independent. It is only independent one level down. - Copying with
b = aand expecting a new object. - Using
deepcopyon objects that cannot be copied, such as open files or locks. These raise an error. - Rebuilding only the level you change. Replacing one inner list with a new one, for example
shallow["tags"] = shallow["tags"] + ["c"], is safe, because+builds a new list and no shared object is mutated.
Exercise
Predict the output, then explain it. import copy data = {"team": ["Ana", "Ben"], "size": 2} c1 = data.copy() c2 = copy.deepcopy(data) c1["team"].append("Cy") c1["size"] = 3 print(data) print(c2)
Show answer
The first print shows {'team': ['Ana', 'Ben', 'Cy'], 'size': 2}. The shallow copy c1 shares the team list with data, so append changes both. Setting c1["size"] = 3 only rebinds the key in c1, so data keeps 2. The second print shows {'team': ['Ana', 'Ben'], 'size': 2}, because the deep copy c2 has its own list and was never touched.
Exercise
A function does def add_bonus(rows): new = rows.copy(); new[0]["score"] += 5; return new. Why does the caller's data change, and how do you fix it?
Show answer
rows.copy() is shallow, so new holds the same dictionaries as rows, and += 5 mutates a shared dictionary. Fix it by using new = copy.deepcopy(rows), or by building new dictionaries, for example new = [dict(r) for r in rows], which is enough here because each row holds only numbers.