Codectionary / Developer documentation / Python

Shallow and Deep Copies

A shallow copy creates an outer container while sharing nested objects. deepcopy recursively copies contained objects while tracking already copied references. Run as a Python 3.11+ script.

Syntax

copy.copy(value); copy.deepcopy(value)

Examples

Shallow and Deep Copies

Run as a Python 3.11+ script.

from copy import copy, deepcopy
original = {"tags": ["new"]}
shallow = copy(original)
deep = deepcopy(original)
shallow["tags"].append("sale")
print(original["tags"])
print(deep["tags"])
  1. Expected output: ['new', 'sale'] ['new']
  2. The shallow dictionary still references the original tags list. The deep copy owns a separate nested list.

Best practices

  • Choose copying based on which nested objects may be mutated.
  • Avoid blindly deep-copying resources such as open files or database connections.

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading