Python / Core Python Fundamentals Interview Questions
What is the difference between a shallow copy and a deep copy in Python?
This distinction matters whenever you have nested or mutable objects and want an independent copy.
An assignment (b = a) creates a second name for the same object — not a copy at all. Mutating b mutates a.
A shallow copy creates a new container object but does not copy the objects inside it — the inner elements are still shared. You get a new list/dict/etc., but any mutable nested objects are referenced, not cloned.
A deep copy recursively copies every object, including nested ones, so the result is completely independent.
import copy original = [[1, 2], [3, 4]] # Shallow copy â new outer list, same inner lists shallow = original.copy() # or list(original) or original[:] shallow[0].append(99) # mutates the shared inner list! print(original) # [[1, 2, 99], [3, 4]] â original changed # Deep copy â new outer AND inner lists original2 = [[1, 2], [3, 4]] deep = copy.deepcopy(original2) deep[0].append(99) print(original2) # [[1, 2], [3, 4]] â original untouched
When to choose each:
- Shallow copy is sufficient when the container holds immutable values (ints, strings, tuples of immutables) or when you intentionally want the copy to share inner objects.
- Deep copy is needed when you want a fully independent snapshot — configuration trees, game states, undo stacks. It is slower and uses more memory.
For dicts, dict.copy() and {**original} are both shallow. The spread operator {**d} is commonly seen in interview code as a one-liner to create a modified copy of a dict without mutating the original.
More Related questions...