Lesson · Copying, Memory & Object Lifecycle
Shallow vs Deep Copy
90 min readShallow vs Deep Copy
Assignment never copies an object by itself. Shallow copy duplicates the outer container while deep copy recursively duplicates reachable state according to Python's copy protocol.
Learning goals
- Explain why
b = acreates a second name rather than a second object, using identity (is) as evidence. - Distinguish what
copy.copyduplicates (the outer container) from what it shares (the nested objects). - Show with
copy.deepcopythat nested mutations stay invisible across the copied graph. - Predict which names see a nested change after each of the three operations.
- Choose a copy depth from the sharing a case allows, including its cost and identity requirements.
Mental model
The three lines differ only in what is new: a name, an outer container, or the entire reachable graph. Asking "what is new here?" before each print in the worked example answers all three outputs.
How deep does the copy go?
shared ids mean one object seen twice
Mental model
the same mechanism as a compact list
assignment: new name → same object shallow copy: new outer → same nested objects deep copy: new outer → copied nested graph
Core idea
The decisive question is what must stay untouched when someone mutates: if nested objects are shared, a shallow copy acts as a window into the original, and if they must diverge, the graph has to be duplicated layer by layer. Python offers both depths through the copy module, and the cost grows with the number of reachable objects, so the choice is a design decision about sharing, not a mechanical default.
Assignment vs copy
b = a binds another name to the same object: no new object exists, and every mutation is visible through both names. A copy creates a new object, and the shallow versus deep question is which of the nested objects are shared with the original and which are duplicated.
copy.copy
copy.copy performs a shallow copy: the outer object is new, but references to nested objects are generally reused.
copy.deepcopy
copy.deepcopy recursively copies reachable objects while tracking already-copied objects to handle cycles and shared references. Types can customize this behavior.
Nested mutable objects
Nested mutable objects are where the shallow and deep distinction shows up: a shallow copy shares the inner lists, so appending through one copy is visible through the other. A deep copy duplicates each reachable mutable object, so the two graphs evolve independently.
Custom copy behavior
Custom copy behavior requires you to decide whether a new outer object, new nested objects, or merely another reference is needed. Draw the object graph when nested mutable state makes the answer unclear.
Walkthrough
original = [[1, 2], [3, 4]]is a list holding two inner lists;copy.copy(original)builds a new outer list whose elements are the same two inner list objects.copy.deepcopy(original)walks the nested lists and builds new inner lists too, so every mutable level of the graph is duplicated.original[0].append(99)mutates the first inner list in place; bothoriginalandshallowsee the change because they share that inner list, whiledeepstays at[1, 2].- Predict before running: the exact three printed lines, and which of the identity checks
original is shallow,original[0] is shallow[0], andshallow[0] is deep[0]are True.
Experiments to try
- Append to
shallowitself (shallow.append(5)) and confirmoriginalis unaffected; the new item exists only in the outer container that was copied. - Print
original[0] is shallow[0]andoriginal[0] is deep[0]and explain the two booleans with the copy depth of each call. - Wrap a shared object two levels deep (
[[{"n": 1}]]) and mutate the dictionary through the shallow copy; then deep-copy the same structure and confirm it is immune. - Benchmark both copies on a large nested structure with
timeitand state how the cost of each method scales with the number of reachable objects.
Playable lesson
Lab: Shallow vs deep copy graph
Draw object-reference graphs for the original, shallow copy, and deep copy. Mutate nested state and reveal which graphs observe the change.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Shallow vs deep copy graph
original
the source graph
shallow = copy.copy(original)
new outer list, shared inner lists (same ids)
deep = copy.deepcopy(original)
new outer and new inner lists (fresh ids)
Identity checks (these never change)
Predict first
After `original[0].append(99)`, which copies show the change?
Predict first
Is `original[0] is shallow[0]` True or False?
Predict first
What does `copy.deepcopy` guarantee that `copy.copy` does not?
Common mistakes
- Reading
copy.copyas "copy": the outer object is new, but mutations through any shared nested object still reach the original. - Expecting
deepcopyto isolate an object that appears twice in the source: its memo keeps one copy per original object, so the alias structure inside the copy is preserved. - Using
==to test whether two names point at the same object: equal contents can come from sharing or from a copy, andisanswers the identity question directly. - Deep-copying shared resources blindly: locks, open files, and caches either cannot be copied or must stay single, and duplicating them breaks the intended sharing.
Practice: Easy
- Run the worked example unchanged and write down the three printed lines; then explain each line with one sentence about what was new.
- Add a third row to
originalbefore copying (original.append([9, 9])), redo the copies, then append tooriginal[2]and compare all three outputs. - Replace
copy.copywithlist(original)and show it behaves the same way; state which of the two forms makes the shallow depth more obvious to a reader.
Practice: Medium
- Deep-copy a structure where the same inner list appears twice (
row = [1]; original = [row, row]), then checkdeep[0] is deep[1]and say what the memo preserved. - Copy a dictionary whose value is a list, mutate the list through the shallow copy, and print both dictionaries; repeat with
deepcopyand state the difference in one sentence. - Write
clone(records)that returns a deep copy of a list of dictionaries, and assert that mutations to the clone do not affect the source; then decide whether a shallow copy would have been sufficient for a read-only consumer.
Practice: Hard
- Build a nested graph with a cycle (
a = []; a.append(a)) and copy it with bothcopy.copyandcopy.deepcopy; explain why the deep copy terminates instead of looping. - Set up a failure lab with three broken expectations: a shallow copy mutated through a shared list, an identity check where
==andisdisagree, and adeepcopyof an object that refuses to be copied; explain each from the copy protocol. - Design a configuration loader that must hand each caller an independent snapshot; choose the copy depth, and specify what happens for values that cannot be copied, such as open files.
Lesson checklist
- I can explain the difference between assignment, shallow copy, and deep copy using the identity of the outer and nested objects.
- I can predict which names see a nested mutation after each operation.
- I can use
copy.copyandcopy.deepcopyand justify the depth for a given case. - I can explain how
deepcopyhandles a cycle or a repeated reference without looping forever.
Remember
Assignment shares one object, a shallow copy duplicates only the outer layer, and a deep copy walks the reachable graph and rebuilds it while preserving internal aliases. Reach for the shallow operation when nested state is read-only or shared on purpose, and pay for `deepcopy` only when independent mutation is genuinely required.
Interview angles
What is the main purpose of **Assignment vs copy**?+
b = a binds another name to the same object: no new object exists, and every mutation is visible through both names. A copy creates a new object, and the shallow versus deep question is which of the nested objects are shared with the original and which are duplicated.
What should you pay attention to when using **copy.copy**?+
copy.copy performs a shallow copy: the outer object is new, but references to nested objects are generally reused.
How does **copy.deepcopy** fit into this lesson?+
copy.deepcopy recursively copies reachable objects while tracking already-copied objects to handle cycles and shared references. Types can customize this behavior.
Why does `deepcopy` keep the alias between two references to the same inner list instead of producing two separate copies?+
deepcopy records every object it has already copied in a memo and returns the recorded copy on later encounters, so the alias structure of the original is preserved. The same memo is why cycles do not send it into an infinite loop.