DEV Community

jackma
jackma

Posted on

Shallow Copy vs Deep Copy in Python: An Interview-Oriented Explanation

One of the most common Python interview questions sounds deceptively simple:

“What’s the difference between shallow copy and deep copy in Python?”

Most candidates can define them.
Fewer can explain when it matters, why bugs happen, and how Python actually implements copying.

In this article, we’ll break down shallow copy and deep copy from an interview perspective, with clear examples and practical reasoning.


1. Why Interviewers Ask This Question

👉 (Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights)

Interviewers use this question to test:

  • Your understanding of mutable vs immutable objects
  • Whether you grasp object references
  • Your ability to reason about side effects and bugs
  • Real-world Python behavior, not just definitions

This is especially important for backend, data, and ML roles.


2. What Is a Shallow Copy?

A shallow copy creates a new container object, but does not recursively copy the objects inside it.

  • The outer object is copied
  • Inner objects are shared references

Example

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)

shallow[0].append(99)

print(original)  # [[1, 2, 99], [3, 4]]
print(shallow)   # [[1, 2, 99], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

Key Observation

  • original and shallow are different lists
  • But their inner lists point to the same memory

3. What Is a Deep Copy?

👉 (Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights)

A deep copy creates a new container and recursively copies all nested objects.

  • No shared references
  • Fully independent structure

Example

import copy

original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)

deep[0].append(99)

print(original)  # [[1, 2], [3, 4]]
print(deep)      # [[1, 2, 99], [3, 4]]
Enter fullscreen mode Exit fullscreen mode

Key Observation

  • Changes in deep do not affect original
  • All nested objects are duplicated

4. Visual Mental Model (Interview-Friendly)

👉 (Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights)

Think of it this way:

  • Shallow copy → copies the box, not the items inside
  • Deep copy → copies the box and everything inside it

This analogy is surprisingly effective in interviews.


5. How to Create Copies in Python

Interviewers often expect you to know multiple ways, not just copy.copy().

Shallow Copy Methods

list.copy()
list[:]
dict.copy()
copy.copy(obj)
Enter fullscreen mode Exit fullscreen mode

Deep Copy Method

copy.deepcopy(obj)
Enter fullscreen mode Exit fullscreen mode

⚠️ Important:

  • Slicing ([:]) is always shallow
  • Assignment (b = a) is not a copy at all

6. Common Interview Traps and Pitfalls

❌ “Shallow copy copies everything once”

→ Incorrect. Nested mutable objects are shared.

❌ “Deep copy is always better”

→ Not true. Deep copy:

  • Is slower
  • Uses more memory
  • May break object identity assumptions

❌ “Immutable objects behave differently”

→ Yes. Immutable objects (e.g., int, str, tuple) don’t cause shared-state issues.


7. Performance and Memory Considerations

Interviewers may ask:

“When should you avoid deep copy?”

Good answer points:

  • Large nested structures
  • Performance-sensitive code
  • Objects holding external resources (files, DB connections)
  • When controlled mutation is acceptable

Deep copy is safe, but not free.


8. Custom Objects and __copy__ / __deepcopy__

Advanced interview insight:

  • Custom classes can control copy behavior
  • Implement:

    • __copy__()
    • __deepcopy__(memo)

This is often used in frameworks and libraries.

Mentioning this briefly signals senior-level understanding.


9. How to Answer This in an Interview (Model Answer)

A strong structured response:

A shallow copy creates a new container but shares references to nested objects, while a deep copy recursively duplicates all objects. Shallow copies are faster and memory-efficient but can cause side effects with mutable nested data. Deep copies avoid shared state but are more expensive. Python provides copy.copy() for shallow copy and copy.deepcopy() for deep copy.

Clear, complete, and concise.


Final Thoughts

Shallow vs deep copy isn’t just a syntax question—it’s about how Python handles references and mutability.

Most real-world Python bugs related to copying come from:

  • Misunderstanding shared references
  • Assuming a copy is fully independent when it’s not

If you understand why these bugs happen, you’ll handle both interviews and production code with much more confidence.

👉 (Want to test your skills? Try a Mock Interview — each question comes with real-time voice insights)

Top comments (0)