🐍 Python Beginner

What is the difference between deep copy and shallow copy in Python?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Python topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

When copying mutable objects, you need to distinguish between reference, shallow, and deep copies. A reference copy (b = a) — both variables point to the same object; changes in one affect the other. A shallow copy creates a new object but copies only references to the nested objects: b = a.copy() or b = list(a) or import copy; b = copy.copy(a). The outer object is new, but nested objects are shared. A deep copy recursively copies all nested objects: b = copy.deepcopy(a). Changes to b (including nested) never affect a. Example: if a list contains a list, a shallow copy of the outer list still shares the inner list. Use deep copy when you need a fully independent duplicate of a complex nested structure.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.