Shallow container duplication
Create an independent outer list or dictionary while intentionally sharing nested values.
Python · Module
Python's copy module provides shallow and deep copying for compound objects. Shallow copies share nested objects, while deep copies recursively duplicate them.
The copy module provides generic shallow and deep copying for compound objects. Shallow copying creates a new outer object but keeps references to contained objects; deep copying recursively copies those contents and tracks already-copied objects with a memo dictionary.
copy.copy(obj)
copy.deepcopy(obj[, memo])
copy.replace(obj, /, **changes)| Name | Type | Description |
|---|---|---|
obj | object | Object to copy. |
memo | dict | Memoization dictionary used by deepcopy to track objects already copied during the current copying pass. |
changes | mapping | Field values used by copy.replace to construct the replacement object. |
copy.copy returns a shallow copy; copy.deepcopy returns a deep copy; copy.replace returns a new object of the same type with specified fields replaced.
from copy import copy, deepcopy
original = {"tags": ["python"]}
shallow = copy(original)
deep = deepcopy(original)
original["tags"].append("backend")
print(shallow["tags"]) # ['python', 'backend']
print(deep["tags"]) # ['python']A shallow copy reuses the nested list, while a deep copy recursively duplicates it.
Create an independent outer list or dictionary while intentionally sharing nested values.
Build an isolated mutable data structure before modifying nested lists, dictionaries, or class instances.
Create a modified immutable-style object by replacing selected supported fields.
copy.copy creates a new compound object and places references to the original's contained objects into it. Mutating a nested mutable value can therefore affect both the original and the shallow copy.
Follow-up: How would you isolate nested mutable values? Use copy.deepcopy, which recursively copies them while tracking objects already processed.
deepcopy accepts an optional memo dictionary internally used to remember objects already copied during the current operation. This supports recursive structures and avoids repeatedly copying the same object.
Follow-up: Why does this matter for cycles? A previously seen object can be reused from the memo instead of causing unbounded recursion.
A class can customize copying by defining __copy__ for shallow copies and __deepcopy__ for deep copies. The latter receives the memo dictionary as its argument.
Follow-up: What should a custom __deepcopy__ implementation do with memo? It should use it when recursively copying components so shared references and cycles are preserved.
copy.copycopy.deepcopycopy.replacecopy.Error__copy__()__deepcopy__()pickle