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"])- Expected output: ['new', 'sale'] ['new']
- 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