How to create a deep copy of an object In Python
Published on Aug. 22, 2023, 12:16 p.m.
In Python, you can create a deep copy of an object using the copy module’s deepcopy() function. This creates a new object and recursively inserts copies of any nested objects within it , rather than creating references to the original objects. Here is an example:
import copy
original_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = copy.deepcopy(original_list)
# Modify the nested list in the new list
new_list[0][0] = 999
# The original list is not modified
print(original_list) # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# The new list has the modified nested list
print(new_list) # [[999, 2, 3], [4, 5, 6], [7, 8, 9]]
In this example, original_list is a list that contains three nested lists. We then create a deep copy of original_list using copy.deepcopy() and store it in the variable new_list. We then modify the first element of the first nested list in new_list. Since new_list is a deep copy of original_list, the modification does not affect original_list, as demonstrated by the final print() statements.