๐ Python Mistakes Everyone Makes ❌
Day 32: Confusing Shallow vs Deep Copy
Copying data structures in Python looks simple—but it can silently break your code if you don’t understand what’s really being copied.
❌ The Mistake
Assuming copy() (or slicing) creates a fully independent copy.
a = [[1, 2], [3, 4]]b = a.copy()b[0].append(99)
print(a)
๐ Surprise: a changes too.
❌ Why This Fails
copy() creates a shallow copy
Only the outer list is duplicated
Inner (nested) objects are shared
Modifying nested data affects both lists
So even though a and b look separate, they still point to the same inner lists.
✅ The Correct Way
Use a deep copy when working with nested objects.
import copya = [[1, 2], [3, 4]]b = copy.deepcopy(a)b[0].append(99)
print(a)
๐ Now a remains unchanged.
๐ง Simple Rule to Remember
✔ Shallow copy → shares inner objects
✔ Deep copy → copies everything recursively
๐ Key Takeaways
Not all copies are equal in Python
Nested data requires extra care
Use deepcopy() when independence matters
Understanding this distinction prevents hidden bugs that are extremely hard to debug later ๐ง ⚠️


0 Comments:
Post a Comment