There are two ways to copy blocks of code in Python: shallow copying or deep copying using the copy module. For lists, direct assignment makes a shallow copy.
How to copy code blocks in Python?
In Python, there are two main ways to copy blocks of code:
copy
module## The #copy module provides
copy and
deepcopy functions for shallow copying and deep copying. Shallow copy only copies the reference of an object, while deep copy recursively copies the object and all its sub-objects.
Shallow copy:
<code class="python">import copy original_list = [1, 2, [3, 4]] copied_list = copy.copy(original_list) # 修改 copied_list 中的嵌套列表 copied_list[2][1] = 5 # 输出 original_list 和 copied_list print(original_list) # [1, 2, [3, 5]] print(copied_list) # [1, 2, [3, 5]]</code>
Deep copy:
<code class="python">import copy original_list = [1, 2, [3, 4]] copied_list = copy.deepcopy(original_list) # 修改 copied_list 中的嵌套列表 copied_list[2][1] = 5 # 输出 original_list 和 copied_list print(original_list) # [1, 2, [3, 4]] print(copied_list) # [1, 2, [3, 5]]</code>
to assign value
<code class="python">original_list = [1, 2, [3, 4]] copied_list = original_list # 修改 copied_list 中的嵌套列表 copied_list[2][1] = 5 # 输出 original_list 和 copied_list print(original_list) # [1, 2, [3, 5]] print(copied_list) # [1, 2, [3, 5]]</code>
The above is the detailed content of How to copy python code. For more information, please follow other related articles on the PHP Chinese website!