A shallow copy creates a new outer container whose elements are the same objects as the original, so mutating a nested list shows up in both. A deep copy recursively copies everything, giving you a fully independent structure. Deep copies cost time and memory and can break on objects holding sockets or file handles, so use them only when nesting is genuinely shared.
Why interviewers ask this
The interviewer is testing your model of names versus objects. Anyone who thinks of variables as boxes holding values will get this wrong, and that same confusion produces subtle bugs where a config template gets mutated by one consumer and every later consumer inherits the change. Mentioning the cost of deep copies, and dunder deepcopy for custom control, shows you have made this decision under real constraints.
How to structure your answer
- Contrast new container versus new contents.
- Give a nested mutation example.
- State the cost of deep copying.
- Say how you decide between them.
Example answer
Shallow means you get a new outer object holding references to the exact same inner objects. Slicing a list of lists gives you a fresh list, but appending to element zero mutates the original too, because both lists point at that same inner list. Deep copy walks the whole graph and rebuilds every level, and it tracks objects it has already seen so cycles do not blow the stack. I default to shallow because it is cheap, and I only reach for deepcopy when I know a nested structure is going to be mutated independently. We had a bug once where a default settings dictionary was copied at the top level only, and a nested retry policy got mutated by one client and applied to every other client on the worker. The other thing worth saying is that deepcopy is not free and it is not always safe. Anything wrapping a database connection or a file handle needs a custom dunder deepcopy or it will fail, or duplicate something it should not.
Walking into this interview soon? GhostPilot listens to your live call, spots the question the moment it is asked, and puts a structured answer on your screen in real time. Try it on your next mock, or grab a $29 Session Pass, no subscription, for the real thing.
See how it worksFollow-up questions to expect
- How does deepcopy handle circular references?
- How would you check whether two names point at the same object?
- When would you make the object immutable instead?
Related python developer questions
Your interviewer will ask their own version of this. Paste your actual job description into the free Question Predictor and get the 20 questions that role is most likely to ask, with what each one is really probing.
Predict my questions