Sub topic 9
Shallow copies versus deep copies
This chapter assumes you can index and loop over nested lists and dictionaries and change them in place. It also assumes you know the shared reference trap from the previous chapter, where [[0] * 3] * 2 produces rows that are the same list. Copying is the other place where that idea causes bugs.
Assignment does not copy
The statement b = a copies nothing. It makes a second name for the same object. Changes made through either name show up through both.
a = {"tags": ["a", "b"]}
b = a
b["owner"] = "Ana"
print(a) # {'tags': ['a', 'b'], 'owner': 'Ana'}
print(a is b) # TrueTo get an independent object, you have to ask for a copy. Python gives you two kinds, and the difference between them matters only when data is nested.
What a shallow copy does
A shallow copy creates one new outer container. It fills that container with references to the same inner objects the original holds. Only the top level is duplicated.
All of these produce a shallow copy of a dictionary:
import copy
original = {"name": "Ana", "tags": ["a", "b"]}
c1 = original.copy()
c2 = dict(original)
c3 = {**original}
c4 = copy.copy(original)
for c in (c1, c2, c3, c4):
print(c is original, c["tags"] is original["tags"])
# False True
# False True
# False True
# False TrueEach copy is a different dictionary (c is original is False), but its "tags" value is the very same list object as the original's.
For lists, the equivalent forms are items.copy(), list(items), items[:], and copy.copy(items). They behave the same way: new outer list, shared elements.
Rebinding versus mutating
A shallow copy can look correct in tests and still fail later. Whether a change leaks depends on what kind of change you make.
original = {"name": "Ana", "tags": ["a", "b"]}
shallow = original.copy()
shallow["name"] = "Ben" # rebinds a key in the copy's own dict
shallow["tags"].append("c") # mutates the shared list
print(original) # {'name': 'Ana', 'tags': ['a', 'b', 'c']}
print(shallow) # {'name': 'Ben', 'tags': ['a', 'b', 'c']}The assignment shallow["name"] = "Ben" changes which object the copy's key points to. The original is unaffected. The call shallow["tags"].append("c") follows the reference to the shared list and changes that list. Both dictionaries see the change, because both point at it.
The rule is simple. Assigning to a slot of the copy is safe. Mutating an object reached through the copy is safe only if that object was itself copied.
The same thing happens with a list of lists:
grid = [[1, 2], [3, 4]]
shallow = grid[:]
shallow[0][0] = 99
print(grid) # [[99, 2], [3, 4]]
shallow.append([5, 6])
print(grid) # [[99, 2], [3, 4]]Appending to the copy leaves the original's length alone, because the outer lists are separate. Writing into shallow[0] changes the row both outer lists share.
What a deep copy does
copy.deepcopy() copies the outer container and then recursively copies everything inside it. No mutable object is shared between the original and the copy.
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']After the deep copy, you can mutate either structure at any depth without affecting the other. This is the safe choice when you need a snapshot, for example to try a change and then compare or roll back.
Immutable values are not duplicated
Integers, strings, None, and other immutable objects can be shared safely, because nobody can change them in place. deepcopy leaves them as they are. A tuple that holds only immutable items is returned as the same object, too.
import copy
t = (1, 2, 3)
print(copy.deepcopy(t) is t) # TrueA tuple that contains a list is different. The tuple itself cannot change, but the list inside it can, so deepcopy builds a new tuple holding a new list.
import copy
t = ([1, 2], 3)
print(copy.copy(t) is t) # True: a shallow copy of a tuple is the tuple
print(copy.deepcopy(t) is t) # False: the inner list had to be copiedThe first line shows a gotcha. copy.copy on a tuple returns the same object, so the list inside is still shared.
How deepcopy handles shared and circular references
deepcopy keeps a memo, a dictionary that maps each object it has already copied to its copy. That gives two useful behaviors.
First, if the original contains the same object twice, the copy contains one new object twice. The sharing structure is preserved:
import copy
shared = [1, 2]
data = {"a": shared, "b": shared}
clone = copy.deepcopy(data)
print(clone["a"] is clone["b"]) # True: still one list, referenced twice
print(clone["a"] is shared) # False: but it is a new listSecond, the memo lets deepcopy handle data that refers back to itself, which would send a naive recursive copier into an infinite loop:
import copy
root = {"name": "root", "children": []}
root["children"].append({"name": "kid", "parent": root})
clone = copy.deepcopy(root)
print(clone["children"][0]["parent"] is clone) # True
print(clone is root) # FalseThe child's "parent" in the clone points to the cloned root, not to the original root. Relationships inside the structure are rebuilt inside the copy.
Choosing between them
| Situation | Better choice | Reason |
|---|---|---|
| Flat list or dict of numbers and strings | Shallow copy | Nothing inside is mutable, so nothing can leak. |
| You will only add, remove, or reassign top-level items | Shallow copy | Those operations touch only the outer container. |
| You will mutate inner lists or dicts of the copy | Deep copy, or copy those levels by hand | Otherwise the original changes too. |
| You need a snapshot to compare or roll back | Deep copy | Later changes at any depth must not affect it. |
| Very large data, and you know which levels change | Copy only those levels | `deepcopy` visits every object and is slow. |
Copying only the levels you will change
A deep copy is the safest default, but it is not free. It is typically many times slower than a hand-written copy of the same shape, and it copies parts you may never touch. When you know the shape, copy the levels that will change and share the rest.
def copy_students(students):
return [{**s, "grades": list(s["grades"])} for s in students]
students = [{"name": "Ana", "grades": [90, 85]}]
edited = copy_students(students)
edited[0]["grades"].append(100)
print(students[0]["grades"]) # [90, 85]
print(edited[0]["grades"]) # [90, 85, 100]This copies the outer list, each student dictionary, and each grades list. It would not be enough if a student had a third mutable level, such as a list of dictionaries. Such helpers must be kept in step with the data's shape. Use deepcopy when the shape varies or when correctness matters more than speed.
Common errors
Believing a shallow copy is independent
The symptom is that "I copied it, but the original changed". Check with is on the inner objects. If copy["key"] is original["key"] is True and the value is a list or dictionary, they are shared.
Copying in the wrong place
Copying after the damage is done does not help. If you want to protect a caller's data inside a function, copy at the start, before any mutation:
import copy
def add_tag(record, tag):
updated = copy.deepcopy(record)
updated["tags"].append(tag)
return updated
before = {"tags": ["a"]}
after = add_tag(before, "b")
print(before) # {'tags': ['a']}
print(after) # {'tags': ['a', 'b']}Using a JSON round trip as a copy
You will sometimes see json.loads(json.dumps(data)) used as a deep copy. It works only for JSON-compatible data, and it changes some values on the way. Tuples come back as lists, integer dictionary keys come back as strings, and objects such as sets or dates raise an error. Prefer copy.deepcopy unless you want JSON's restrictions.
Expecting deepcopy to copy everything
deepcopy copies most built-in containers and ordinary class instances. Some objects cannot be copied in a meaningful way, such as open files or locks, and trying may raise an error. A class can customize its behavior by defining __copy__ and __deepcopy__ methods. Reach for that only when you control the class and the default is wrong.
Deep-copying inside a loop
Calling deepcopy on a large structure on every iteration can dominate your running time. Copy once outside the loop if you can, or copy only the parts that change.
Summary of rules
- Assignment makes another name, not a copy.
- A shallow copy duplicates one level. Everything below it is shared.
- A deep copy duplicates every level and preserves internal sharing and cycles.
- Reassigning a key in the copy is safe with either kind. Mutating a shared inner object is not.
- Copy before you mutate, and copy only as deep as you need.
Exercise
Given a = {"scores": [1, 2], "label": "x"} and b = a.copy(), you run b["label"] = "y" and then b["scores"].append(3). What are a["label"] and a["scores"] afterward, and why? Which one-line change to the first copy would stop a["scores"] from changing?
Show answer
a["label"] is still "x" and a["scores"] is [1, 2, 3]. Assigning to b["label"] rebinds a key in the copy's own dictionary, so a is unaffected. b["scores"] is the same list object as a["scores"], so the append is visible through both. Using b = copy.deepcopy(a) (after import copy) gives b its own scores list, and a["scores"] stays [1, 2].
Exercise
A function receives matrix = [[1, 2], [3, 4]] and must return a new matrix with every value doubled, leaving the argument unchanged. A colleague writes result = matrix[:] and then doubles each value in place with nested loops. Explain what goes wrong, and write a version that works without calling copy.deepcopy.
Show answer
matrix[:] is a shallow copy, so result holds the same row lists as matrix. Doubling values in place through result changes the rows of the original too. A version that builds new rows works: result = [[value * 2 for value in row] for row in matrix]. Each inner list comprehension creates a fresh row, so matrix is never modified.
Exercise
You run import copy, t = ([1, 2], 3), u = copy.copy(t), and u[0].append(99). What does t contain, and does u is t hold?
Show answer
t is ([1, 2, 99], 3), and u is t is True. A shallow copy of a tuple returns the same tuple object, so there is only one list, and the append changes it. Using copy.deepcopy(t) would return a new tuple with its own copy of the list.