copy
The Python copy
module provides functionality to create shallow copy and deep copies of objects in Python.
This module is useful when you need to duplicate objects while ensuring that the original and the copy can be modified independently.
Here’s a quick example:
>>> import copy
>>> original = [1, 2, [3, 4]]
>>> duplicate = copy.deepcopy(original)
>>> duplicate[2][0] = "changed"
>>> original
[1, 2, [3, 4]]
>>> duplicate
[1, 2, ['changed', 4]]
Key Features
- Creates shallow copies of objects
- Creates deep copies of objects
- Ensures independent modification of copies from originals
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
copy.copy() |
Function | Creates a shallow copy of an object |
copy.deepcopy() |
Function | Creates a deep copy of an object |
Examples
Creating a shallow copy of a list:
>>> original = [1, 2, 3]
>>> shallow_copy = copy.copy(original)
>>> shallow_copy is original
False
Creating a deep copy of a nested list:
>>> original = [1, 2, [3, 4]]
>>> deep_copy = copy.deepcopy(original)
>>> deep_copy[2][0] = "changed"
>>> original
[1, 2, [3, 4]]
Common Use Cases
- Duplicating complex objects without shared references
- Ensuring that modifications to copies don’t affect the original object
- Creating backup states of objects for undo functionality
Real-World Example
Suppose you’re working on a project where you need to maintain versions of a configuration dictionary. You can use the copy
module to create deep copies of the configuration at different states:
>>> import copy
>>> config = {"dark": True, "coordinates": [1, 2, 3]}
>>> config_user = copy.deepcopy(config)
>>> config_user["coordinates"][2] = 4
>>> config
{'dark': True, 'coordinates': [1, 2, 3]}
>>> config_user
{'dark': True, 'coordinates': [1, 2, 4]}
By using copy.deepcopy()
, you ensure that modifications to config_user
don’t affect config
, allowing for independent version management.
Related Resources
Tutorial
How to Copy Objects in Python: Shallow vs Deep Copy Explained
Understand the difference between shallow and deep copies in Python. Learn how to duplicate objects safely using the copy module and other techniques.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated June 26, 2025