copy.copy, copy.deepcopy
copy.copy(x)
copy.deepcopy(x[, memo])Make a shallow or deep copy of a compound object. After a shallow copy, nested mutable objects are still shared.
| Parameter | Description |
|---|---|
x | The object to copy. Lists, dicts, and user-defined objects are typical compound values. |
memo | An optional dict that deepcopy uses to track objects already copied in this pass. Ordinary callers can omit it. |
Returns: A new object. For a shallow copy of a list, the new list is a different object, but its elements may be the original elements.
Raises
copy.Error / TypeError— Raised when an object cannot be copied, for example some system objects that official documentation lists as not copied.
- The example mutates the inner list after both copies exist, so you can compare shared and independent references in one run.
import copy
inner = [1]
outer = [inner, 2]
shallow = copy.copy(outer)
deep = copy.deepcopy(outer)
shallow[0][0] = 8
shallow[1] = 9
print(outer, shallow, shallow[0] is outer[0])
print(deep, deep[0] is outer[0])
deep[0][0] = 7
print(outer, deep)Expected output
[[8], 2] [[8], 9] True
[[1], 2] False
[[8], 2] [[7], 2]