How to Deep Copy Nested List in Python: Simple Guide
To deep copy a nested list in Python, use the
deepcopy() function from the copy module. This creates a new list with all inner lists copied recursively, so changes to the copy do not affect the original.Syntax
Use the deepcopy() function from the copy module to create a deep copy of a nested list.
copy.deepcopy(obj): Returns a new object that is a deep copy ofobj.obj: The nested list or any object you want to copy deeply.
python
import copy
new_list = copy.deepcopy(original_list)Example
This example shows how to deep copy a nested list so that changes to the copy do not affect the original list.
python
import copy original_list = [[1, 2], [3, 4]] shallow_copy = original_list.copy() # Only copies outer list deep_copy = copy.deepcopy(original_list) # Copies all nested lists # Change an element in the nested list of shallow_copy shallow_copy[0][0] = 100 # Change an element in the nested list of deep_copy deep_copy[1][1] = 400 print("Original List:", original_list) print("Shallow Copy:", shallow_copy) print("Deep Copy:", deep_copy)
Output
Original List: [[100, 2], [3, 4]]
Shallow Copy: [[100, 2], [3, 4]]
Deep Copy: [[1, 2], [3, 400]]
Common Pitfalls
A common mistake is using list.copy() or slicing (list[:]) which only creates a shallow copy. This means nested lists are still shared between the original and the copy, so changes to nested elements affect both.
Always use copy.deepcopy() for nested lists to avoid this problem.
python
import copy original = [[1, 2], [3, 4]] shallow = original.copy() # Shallow copy shallow[0][0] = 99 print("Original after shallow copy change:", original) # Shows changed nested list # Correct way original = [[1, 2], [3, 4]] deep = copy.deepcopy(original) deep[0][0] = 99 print("Original after deep copy change:", original) # Original unchanged
Output
Original after shallow copy change: [[99, 2], [3, 4]]
Original after deep copy change: [[1, 2], [3, 4]]
Quick Reference
- Shallow copy:
list.copy()orlist[:]copies only the outer list. - Deep copy:
copy.deepcopy(list)copies all nested lists recursively. - Use deep copy to avoid shared references in nested structures.
Key Takeaways
Use copy.deepcopy() to create a deep copy of nested lists in Python.
Shallow copies only duplicate the outer list, not nested lists inside.
Changes to nested elements in shallow copies affect the original list.
Deep copying prevents unexpected side effects when modifying nested lists.
Always import the copy module before using deepcopy.