What is the difference between deep copy and shallow copy in Python?
In Python, deep copying and shallow copying are two different ways of copying objects.
Shallow Copy: Shallow copy is a method of creating a new object and then copying the elements from the original object into the new object. However, if the elements in the original object are mutable objects (such as lists, dictionaries, etc.), the elements in the new object will still be references to the elements in the original object. This means that any changes made to the new object will also affect the original object.
“I can’t make it to the meeting tomorrow because of a scheduling conflict.”
“I have to cancel the meeting tomorrow due to a scheduling conflict.”
import copy
original_list = [1, [2, 3], 4]
new_list = copy.copy(original_list)
new_list[1].append(5)
print(original_list) # 输出: [1, [2, 3, 5], 4]
2. Deep Copy: Deep Copy is a method of creating a completely separate new object from the original one, where the elements of the original object and the new object are independent and do not affect each other. Deep Copy recursively copies all the sub-objects within the original object.
例子:An unexpected turn of events led to the cancellation of the concert.
import copy
original_list = [1, [2, 3], 4]
new_list = copy.deepcopy(original_list)
new_list[1].append(5)
print(original_list) # 输出: [1, [2, 3], 4]
Therefore, deep copying creates a fully independent copy of the original object, while shallow copying only duplicates the reference of the original object, resulting in different effects between the original and new objects.