Python Reference ยท Standard Library: Data Structures and Functional Tools
The copy module
Reference for Python's copy module: shallow copy vs deep copy, how deepcopy handles cycles, custom __copy__ and __deepcopy__, and when slicing is enough.
The copy module makes copies of objects whose type Python does not already know how to duplicate. Assignment (b = a) never copies anything: it only gives the same object a second name. When you need an independent object, you have two choices. copy.copy() makes a shallow copy: a new outer container that still shares the inner objects. copy.deepcopy() makes a deep copy: the container and everything reachable from it are duplicated recursively.
For the common built-in containers you often do not need the module at all: list(x), x[:], x.copy(), dict(x) and set(x) are all shallow copies. Reach for copy when the structure is nested, when it contains instances of your own classes, or when you want one function that works for any type.
import copy original = [[1, 2], [3, 4]] clone = copy.deepcopy(original)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
What is in the module
| Name | Description |
|---|---|
copy.copy(x) |
Returns a shallow copy of x. |
copy.deepcopy(x, memo=None) |
Returns a deep copy of x. memo is an internal dictionary of objects already copied. |
copy.replace(x, **changes) |
Returns a copy of x with some fields changed (added in Python 3.13). Works with dataclasses, named tuples, datetime objects and classes that define __replace__. |
copy.Error |
Raised when an object cannot be copied. |
Return value: a new object of the same type (or the very same object for immutable atomic types).
Raises: copy.Error or TypeError for objects that cannot be copied, such as modules, open files or locks.
Usage notes
- Shallow copies share the inner objects. Changing
shallow[0]in place changes the original too. Rebindingshallow[0] = [...]does not. - Immutable values are returned as is.
copy.copy(5),copy.copy("text")and copies of tuples that hold only immutable items give back the same object, and that is fine because it cannot change. - Tuples with mutable items:
copy.deepcopy()duplicates the mutable parts;copy.copy()returns the same tuple. - Cycles and shared references are preserved. The
memodictionary mapsid(obj)to the copy, so an object reachable twice is copied once, and self-referencing structures do not recurse forever. - Deep copies can be slow and large. Everything reachable is duplicated, including caches, parent links and large buffers. Copy only the part you need, or define
__deepcopy__. - Customize with
__copy__and__deepcopy__.__deepcopy__(self, memo)should passmemoto nesteddeepcopycalls. Without these methods the module uses the same protocol aspickle(__reduce_ex__,__getstate__). - Not everything copies. Files, sockets, locks, modules and generators raise errors. Functions, classes and modules are treated as atoms and returned unchanged by
deepcopywhere that is meaningful. - Do not deep copy to avoid thinking about mutation. Often an immutable approach (
tuple,frozenset, building a new list) is simpler and faster. - Dataclasses:
dataclasses.replace(obj, field=value)makes a changed shallow copy; on 3.13+copy.replace()does the same for more types.
Related
list,dict,setdataclasses,pickle- Lessons: Lists, Memory management