How to Use Copy Module in Python: Syntax and Examples
Use the
copy module in Python to create shallow or deep copies of objects. Import it with import copy, then use copy.copy() for a shallow copy and copy.deepcopy() for a deep copy.Syntax
The copy module provides two main functions:
copy.copy(obj): Creates a shallow copy ofobj. It copies the object but not nested objects inside it.copy.deepcopy(obj): Creates a deep copy ofobj. It copies the object and all nested objects recursively.
First, import the module with import copy.
python
import copy
shallow_copy = copy.copy(original_object)
deep_copy = copy.deepcopy(original_object)Example
This example shows the difference between shallow and deep copy using a list that contains another list inside it.
python
import copy original = [1, 2, [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original) # Change nested list in shallow copy shallow[2][0] = 'changed' print('Original:', original) print('Shallow copy:', shallow) print('Deep copy:', deep)
Output
Original: [1, 2, ['changed', 4]]
Shallow copy: [1, 2, ['changed', 4]]
Deep copy: [1, 2, [3, 4]]
Common Pitfalls
A common mistake is to use copy.copy() when you need a full independent copy of nested objects. Shallow copy only copies the outer object, so changes to nested objects affect both copies.
Always use copy.deepcopy() if you want to avoid shared nested objects.
python
import copy original = [[1, 2], 3] shallow = copy.copy(original) shallow[0][0] = 'oops' print('Original after shallow copy change:', original) # Correct way original = [[1, 2], 3] deep = copy.deepcopy(original) deep[0][0] = 'safe' print('Original after deep copy change:', original)
Output
Original after shallow copy change: [['oops', 2], 3]
Original after deep copy change: [[1, 2], 3]
Quick Reference
| Function | Description |
|---|---|
| copy.copy(obj) | Shallow copy: copies object but shares nested objects |
| copy.deepcopy(obj) | Deep copy: copies object and all nested objects |
| import copy | Import the copy module to use its functions |
Key Takeaways
Import the copy module with import copy to use copying functions.
Use copy.copy() for a shallow copy that shares nested objects.
Use copy.deepcopy() for a full independent copy including nested objects.
Shallow copies can cause bugs if nested objects are modified.
Deep copy is safer for complex objects but slower.