How to Deep Copy a List in Python: Simple Guide
To deep copy a list in Python, use the
deepcopy() function from the copy module. This creates a new list with all nested objects copied, so changes to the copy do not affect the original list.Syntax
Use the deepcopy() function from the copy module to create a deep copy of a list. This copies the list and all objects inside it recursively.
import copy: Imports the copy module.copy.deepcopy(original_list): Returns a new list that is a deep copy oforiginal_list.
python
import copy
new_list = copy.deepcopy(original_list)Example
This example shows how to deep copy a list containing nested lists. Modifying the deep copy does not change the original list.
python
import copy original = [1, 2, [3, 4]] copy_list = copy.deepcopy(original) copy_list[2][0] = 99 print("Original list:", original) print("Deep copied list:", copy_list)
Output
Original list: [1, 2, [3, 4]]
Deep copied list: [1, 2, [99, 4]]
Common Pitfalls
Using list() or slicing [:] only creates a shallow copy. Nested objects inside the list still refer to the same objects, so changes affect both lists.
Always use copy.deepcopy() when you want a full independent copy of nested lists or objects.
python
original = [1, 2, [3, 4]] shallow_copy = original[:] shallow_copy[2][0] = 99 print("Original after shallow copy change:", original) import copy deep_copy = copy.deepcopy(original) deep_copy[2][0] = 100 print("Original after deep copy change:", original)
Output
Original after shallow copy change: [1, 2, [99, 4]]
Original after deep copy change: [1, 2, [3, 4]]
Quick Reference
- Shallow copy:
new_list = original_list[:]orlist(original_list) - Deep copy:
import copythennew_list = copy.deepcopy(original_list) - Use deep copy for nested lists or objects to avoid shared references.
Key Takeaways
Use copy.deepcopy() to create a fully independent copy of a list with nested objects.
Shallow copies only duplicate the outer list, not nested objects inside it.
Import the copy module before using deepcopy().
Modifying a deep copied list does not affect the original list.
For simple flat lists, shallow copy methods may be enough, but prefer deepcopy for safety.