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
- Assess whether your collection contains nested mutables.
- If not, a shallow copy is sufficient:
new = old[:]ornew = old.copy(). - If yes, import
copyand usecopy.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)andold.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.