深度阅读

How to create a deep copy of an object In Python

作者
作者
2023年08月22日
更新时间
10.5 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。