Copy vs Deep Copy
Learn shallow vs deep copying with nested structures, why shallow copy breaks in nested lists/dicts, and the correct fixes with examples.
Copying is easy when data is flat, but tricky when nested. ## Shallow copy vs deep copy - Shallow copy copies the outer container only - Deep copy copies everything inside (nested items too) ## Shallow copy example (problem) ```python a = [[1, 2], [3, 4]] b = a.copy() b[0].append(99) print(a) # [[1,2,99],[3,4]] <-- changed! print(b) ``` Why? Because inner lists are still shared. ## Deep copy (solution) ```python import copy a = [[1, 2], [3, 4]] b = copy.deepcopy(a) b[0].append(99) print(a) # [[1,2],[3,4]] print(b) # [[1,2,99],[3,4]] ``` ## Graph: shallow vs deep ```mermaid flowchart LR A[Outer list] --> B[Inner list 1] A --> C[Inner list 2] D[Shallow copy] --> B D --> C E[Deep copy] --> F[New inner list 1] E --> G[New inner list 2] ``` ## Remember - Shallow copy is fine for flat structures - Nested structures often need deepcopy - Know this to avoid hidden bugs