Python interview questionsQuestion 1 of 9
Python interview question · Question 1 of 9
Explain shallow copy vs deep copy.
Short answer
A shallow copy creates a new outer container, but fills it with references to the same inner objects. So if you change a nested list or dict through the copy, the original changes too. A deep copy, made with `copy.deepcopy`, copies the nested objects as well, at every level, so the two are completely independent. Shallow copies are cheaper and fine for flat data. Use a deep copy when you will change nested data, such as a JSON-like config, and must leave the original untouched.
On this page
Detailed explanation
import copy
config = {"tables": ["orders", "customers"], "retries": 3}
shallow = copy.copy(config)
deep = copy.deepcopy(config)
shallow["tables"].append("products") # mutates the shared inner list
shallow["retries"] = 5 # rebinds a key on the copy only
print(config)
print(deep)
{'tables': ['orders', 'customers', 'products'], 'retries': 3}
{'tables': ['orders', 'customers'], 'retries': 3}
Appending through the shallow copy changed the original’s list, because both dicts point to the same list object. Reassigning retries did not, because that replaced the value on the copy only. The deep copy is unaffected by either change.
Shallow copies you may not notice
list(x), x[:], x.copy(), dict(x) and {**x} all make shallow copies.
When it matters in pipelines
A shared default configuration or a template record that each task “copies” and then modifies. With nested structures and a shallow copy, one task’s change leaks into every other task’s config.
Common mistakes
- Assuming
.copy()makes nested data independent. - Using
deepcopyon large objects in a hot loop (it is slow), when building fresh objects would be clearer. - Forgetting that immutable nested values (strings, numbers, tuples of immutables) are safe to share.
Progress is saved in this browser only. No account needed.

