What are the best practices for copying and deep copying collections?

· Category: Python Programming

Short answer

Use slicing ([:]) or .copy() for shallow copies when the collection contains only immutable items. Use copy.deepcopy() when the collection contains nested mutable objects that must also be copied independently.

Steps

  1. Assess whether your collection contains nested mutables.
  2. If not, a shallow copy is sufficient: new = old[:] or new = old.copy().
  3. If yes, import copy and use copy.deepcopy(old).
import copy

# Shallow copy
original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0][0] = 99
print(original[0][0])   # 99 (affected!)

# Deep copy
deep = copy.deepcopy(original)
deep[0][0] = 100
print(original[0][0])   # 99 (unchanged)

Tips

  • For dictionaries, dict(old) and old.copy() create shallow copies.
  • list(old) creates a shallow copy of a list.
  • Deep copying is slower and uses more memory; use it only when necessary.
  • Custom classes can implement __copy__ and __deepcopy__ to control copying behavior.

Common issues

  • Assignment (new = old) does not copy; it creates a new reference to the same object.
  • Shallow copies share references to nested mutable objects, leading to surprising mutations.
  • Deep copying objects with circular references can be tricky, but copy.deepcopy() handles them by default.