🐍 Python
Beginner
What is the difference between deep copy and shallow copy in Python?
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.