Skip to content

Shallow copy leaves nested references shared

Quick summary

You used copy.copy() and modified a nested object — both the original and copy share the same nested reference, so both are affected.

Why this happens

  • You used copy.copy() or list slicing [:] which only copies the top level, not nested mutable objects

  • A nested list or dict in the copy is the same object as in the original, so in-place mutations affect both

  • You assumed shallow copy creates independent nested objects, but it only duplicates the outer container

Minimal example

✗ Broken code
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0].append(99)
print(original)  # [[1, 2, 99], [3, 4]] — original mutated!
✓ Fixed code
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original)  # [[1, 2], [3, 4]] — original unchanged

deepcopy recursively duplicates all nested objects, so modifying the copy's nested list does not affect the original.

How to diagnose

  • After copying, modify a nested object in the copy and check if the original is also modified

  • Use id() to compare the nested object addresses in the original and copy — if they match, it is a shared reference

  • Print the original after modifying the copy to detect shared nested references

How to fix

  • Use copy.deepcopy() to recursively copy all nested objects, creating fully independent copies

  • Reconstruct the nested objects manually with a list comprehension or dict comprehension that copies each element

  • Use a custom __copy__ or __deepcopy__ method if your objects need special copy behavior

How to prevent

  • Use copy.deepcopy() whenever you need a fully independent copy of a nested data structure

  • Understand the difference between shallow copy (copy.copy) and deep copy (copy.deepcopy) before choosing

Related Resources

Related Lessons

← Back to language