In Python, a shallow copy and a deep copy are two ways of creating a copy of an object. The main difference between the two is the level of copying involved.
A shallow copy creates a new object, but it only copies the reference of the original object to the new object. This means that changes made to the original object will also be reflected in the shallow copy. In other words, a shallow copy creates a new object with the same reference to the original object.
A deep copy, on the other hand, creates a new object and recursively copies all the nested objects as well. This means that changes made to the original object will not be reflected in the deep copy. In other words, a deep copy creates a completely new object that is a copy of the original object, with no shared references to the original object.
Here is an example to illustrate the difference between a shallow copy and a deep copy:
import copy # Original list original_list = [1, 2, [3, 4], 5] # Shallow copy shallow_copy = copy.copy(original_list) # Deep copy deep_copy = copy.deepcopy(original_list) # Change the nested list in the original list original_list[2][0] = 100 # Output print(original_list) # [1, 2, [100, 4], 5] print(shallow_copy) # [1, 2, [100, 4], 5] print(deep_copy) # [1, 2, [3, 4], 5]
In this example, the original list contains a nested list. When we make a shallow copy of the original list, changes made to the nested list in the original list are also reflected in the shallow copy. However, when we make a deep copy of the original list, changes made to the nested list in the original list are not reflected in the deep copy.
0 Comments