copy — shallow and deep copy

copy.copy versus copy.deepcopy, including shared inner lists after a shallow copy and independent nested objects after a deep copy.

モジュールページの本文は現在英語です。

The copy module provides generic shallow and deep copying. Official documentation states that the difference matters only for compound objects. A shallow copy builds a new container and inserts the same inner objects that the original holds. A deep copy builds a new container and recursively copies those inner objects.

copy.deepcopy keeps a memo table so cyclic structures do not recurse forever. Official documentation also says that some objects, such as modules, functions, and files, are not copied. Classes can customize the operation with __copy__ and __deepcopy__.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Shallow copy versus deep copy

copy.copy(outer) shares the inner list: assigning to shallow[0][0] also changes outer[0][0], while replacing shallow[1] with a new integer does not change outer[1] because integers were rebound, not mutated. copy.deepcopy(outer) gives a new inner list, so later writes to deep[0] do not change outer. is checks confirm whether the inner list is the same object.

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.

ParameterDescription
xThe object to copy. Lists, dicts, and user-defined objects are typical compound values.
memoAn 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.
python
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]

Official documentation →