What is the difference between a shallow copy and a deep copy of an object?
A shallow copy duplicates the object but shares the objects it refers to. A deep copy duplicates the whole graph, so the copy shares nothing with the original.
Explain it simply
Photocopying a folder of documents is a deep copy. Making a new folder that holds the same original papers is a shallow copy: two folders, one set of papers. Edit a paper through either folder and both see it.
This matters when an object holds lists, dictionaries or other objects.
Example
import copy
original = {"name": "Asha", "marks": [80, 90]}
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original["marks"].append(100)
print(shallow["marks"]) # [80, 90, 100] (shared list)
print(deep["marks"]) # [80, 90] (independent list)In Java the same idea appears with clone(), which is shallow by default, and with copy constructors that you write to copy nested objects yourself.
What to say in the interview
"A shallow copy creates a new top-level object but its fields still point to the same nested objects. A deep copy recursively copies nested objects as well. I use deep copy when the copy must be modified independently, accepting the extra cost."
Common mistakes
- Thinking list(x) or x[:] copies nested lists too. It does not.
- Using Java's clone() and assuming it is deep.