The difference between Python’s deep copy and shallow copy

In Python, object assignment and copying are different because they involve referencing and copying objects. When you create a new variable using an assignment statement, they will reference the same object. In some cases, you may want to create a completely independent object, in which case a copy is required.

Copy in Python is divided into deep copy and shallow copy:

Shallow copy: It only copies the reference to the object, not the object itself. The original object and the copied object share the same memory address. This means that if you modify the copied object, the original object will be affected because they are actually the same object. Shallow copies can be created using slicing, the copy() method, or factory functions.

Deep copy: It recursively copies an object and all its sub-objects, rather than copying their references. A deep copy creates a completely independent object in memory, so modifications to the copied object will not affect the original object. Deep copies can be created using the deepcopy() function in the copy module.

Here is some sample code to better understand these concepts:

import copy

# 浅拷贝示例
list1 = [[1, 2], [3, 4]]
list2 = list1.copy()
list1[0][0] = 5
print(list2)   # Output: [[5, 2], [3, 4]]

# 深拷贝示例
list1 = [[1, 2], [3, 4]]
list2 = copy.deepcopy(list1)
list1[0][0] = 5
print(list2)   # Output: [[1, 2], [3, 4]]

In the above code, we first create a list list1 which contains two sublists. We then created a new list list2 using a shallow copy, which references the same sublist. When we modify the first sublist in list1, list2 will also be modified since they share the same sublist.

Next, we use a deep copy to create list2, which contains a complete copy of list1, including sublists. When we modify the first sublist in list1, list2 will not be modified because they have different sublists.

Guess you like

Origin blog.csdn.net/qq_39962271/article/details/129332520