What is the difference between a shallow copy and a deep copy?
⚡ Short Answer
A shallow copy duplicates the outer object but shares references to the nested objects, so mutating a nested item shows up in both copies. A deep copy (`copy.deepcopy`) recursively duplicates everything, giving a fully independent object. Assignment (`b = a`) copies nothing — both names point to the same object.
☕Coffee Chat Question
Concept Made Simple
“What is the difference between a shallow copy and a deep copy?”
🧠Mind Map Answer
Remember It Faster
⌨️Hands-on Keyboard
Learn by Doing
import copy
a = [[1, 2], [3, 4]]
shallow = a[:] # or list(a)
shallow[0][0] = 99 # affects a too!
print(a) # [[99, 2], [3, 4]]
deep = copy.deepcopy(a)
deep[0][0] = 0 # a untouched
print(a) # [[99, 2], [3, 4]][[99, 2], [3, 4]] [[99, 2], [3, 4]]
🔥What If?
Think Beyond the Expected
You copied a list of lists with `new = old[:]` and editing new[0][0] changed old too — why?
`old[:]` is a shallow copy: it makes a new outer list but the inner lists are the SAME objects shared by both. Editing a nested list mutates the shared object. Use copy.deepcopy(old) when you need the nested objects duplicated too.
😂Real World
This bites people who copy nested config/state to 'safely' edit it and accidentally mutate the original; knowing shallow vs deep prevents subtle shared-state bugs.
🎯Interviewer's Expectation
Keywords they're listening for:
⚠️Common Mistakes
- ✗Assuming [:] deep-copies nested structures
- ✗Thinking `b = a` makes a copy
- ✗Using deepcopy everywhere (needless cost)
✅Best Practices
- ✓Use deepcopy only when nested independence is needed
- ✓Prefer immutable data to avoid copy questions
- ✓Know [:]/copy()/dict() are shallow
🔁Follow-up Questions
- 1How do you shallow-copy a dict?
- 2Why is deepcopy slower / when to avoid it?
- 3How does this relate to mutable default arguments?
🧩Related Technologies
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Data Types (Python) Interview question: "What is the difference between a shallow copy and a deep copy?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.