← All notes

Python copy: shallow copy, deepcopy and copy.replace

Answer: Use copy.copy(obj) for a shallow copy and copy.deepcopy(obj) when nested mutable objects must not be shared. Assignment does not copy objects; it only creates bindings between a target and an object.

Examples

import copy
from dataclasses import dataclass

grid = [[0, 0], [0, 0]]
alias = grid                    # same object
shallow = copy.copy(grid)       # new outer list, same inner lists
deep = copy.deepcopy(grid)      # new inner lists too

shallow[0][0] = 1
print(grid[0][0])               # 1 - inner list is shared
print(deep[0][0])               # 0

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p2 = copy.replace(Point(1, 2), y=5)   # Python 3.13+

Shallow versus deep

Deep copy pitfalls

Recursive objects may cause a recursive loop, and deep copy may copy too much, such as data meant to be shared. deepcopy() avoids these problems with a memo dictionary of objects already copied, and lets classes override the copying.

Customizing

Not copied

Modules, methods, stack frames, files and sockets are not copied. Functions and classes are returned unchanged.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, copy - Shallow and deep copy operations; python/cpython (GitHub), Lib/copy.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, copy - Shallow and deep copy operations; python/cpython (GitHub), Lib/copy.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:y53a3c0n

iinventedlight. 2026. "Python copy: shallow copy, deepcopy and copy.replace." iinventedlight Library, iil:note:y53a3c0n, version of 2026-11-18. https://iinventedlight.com/library/notes/python-copy/. License: CC-BY-4.0.

@misc{iil_note_y53a3c0n,
  author = {{iinventedlight}},
  title = {{Python copy: shallow copy, deepcopy and copy.replace}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/python-copy/},
  note = {Permanent ID iil:note:y53a3c0n. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-copy.md.