PYTHON
Performing a Deep Copy of Nested Python Data Structures
Learn how to create a complete, independent copy of nested lists or dictionaries in Python using `copy.deepcopy` to avoid shared references and unintended side effects.
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
deep_copied_list = copy.deepcopy(original_list)
# Modify the deep copied list
deep_copied_list[0][0] = 99
print(f"Original list: {original_list}")
print(f"Deep copied list: {deep_copied_list}")
original_dict = {'a': {'x': 1}, 'b': [2, 3]}
deep_copied_dict = copy.deepcopy(original_dict)
deep_copied_dict['a']['x'] = 100
deep_copied_dict['b'].append(4)
print(f"
Original dictionary: {original_dict}")
print(f"Deep copied dictionary: {deep_copied_dict}")
How it works: `copy.deepcopy()` creates a new, independent copy of a compound object and recursively copies all objects found within it. This is crucial for nested mutable data structures like lists of lists or dictionaries containing lists/dictionaries. Unlike a shallow copy (`copy.copy()` or slicing), deep copy ensures that modifications to the copied structure, even at nested levels, do not affect the original object, preventing unexpected bugs related to shared references.