copy.deepcopy
时间: 2023-11-20 08:07:24 浏览: 98
The `copy.deepcopy()` method is a function in Python's `copy` module that creates a deep copy of an object. A deep copy creates a new object and recursively copies all nested objects as well. This means that any changes made to the original object will not affect the copy, and vice versa.
Here's an example of how to use `copy.deepcopy()`:
```
import copy
original_list = [1, 2, [3, 4]]
deep_copy_list = copy.deepcopy(original_list)
# Modify the original list
original_list[2][0] = 5
print(original_list) # Output: [1, 2, [5, 4]]
print(deep_copy_list) # Output: [1, 2, [3, 4]]
```
In this example, `original_list` contains a nested list. When we create a deep copy of `original_list` and modify the nested list in `original_list`, the nested list in `deep_copy_list` remains unchanged. This is because `copy.deepcopy()` created a new nested list in `deep_copy_list` instead of referencing the original nested list.
阅读全文