Interview frequency: …
Short answer
A shallow copy creates a new container whose inner elements are the same objects, while a deep copy recursively copies the whole object graph, handling circular references.
Explanation
Start with a shallow copy (list(x), x.copy() or copy.copy) when the elements are immutable or sharing is intended. deepcopy is slower and may not suit objects such as connections, locks and file handles. A class can control copying through __copy__ and __deepcopy__. In many cases building a new object with the required fields is clearer than deepcopy.
Code example
from copy import copy, deepcopy
settings = {"tags": ["a"]}
shallow = copy(settings)
deep = deepcopy(settings)
shallow["tags"].append("b")
print(settings["tags"]) # ['a', 'b'] — Shared
print(deep["tags"]) # ['a']Common mistakes
- Using dict.copy() to protect nested settings from modification.
- Calling deepcopy on large objects in hot paths without measuring.