What is the difference between a shallow copy and a deep copy, and when does the difference actually bite?
Answer
A shallow copy, made with `list(original)`, `original.copy()` or `copy.copy()`, creates a new outer container but still references the same nested objects as the original. A deep copy, made with `copy.deepcopy()`, recursively copies nested objects too, using an internal memo dictionary to preserve shared references and safely handle cyclic structures, so mutating an ordinary nested object inside the copy usually no longer affects the original. This is not an absolute guarantee of total independence, though: `deepcopy` leaves some objects (like functions, classes and modules) unchanged rather than copying them, and a class can customize its own copying behavior via `__deepcopy__`. Either way, the difference bites whenever the container holds mutable nested objects: mutating a nested list inside a shallow copy also mutates that same nested list inside the original, which is a common source of hard-to-trace bugs.
Strong answer includes
- shallow copy shares nested mutable objects
- deep copy recursively copies nested objects via a memo, without promising total independence
- bug surfaces when nested containers are mutated
Practical example
Run the code to see the result.
The shallow copy creates a new outer list but shares both inner lists with original. deepcopy recursively creates independent nested containers for this ordinary list structure.
Expected result: original and shallow both contain 9 in the first nested list; only deep contains 8 in the second nested list.