In Python, a copy of an object can be created using either a shallow copy or a deep copy. Here’s an explanation of the differences between these two types of copies and how to create them:
Shallow copy: A shallow copy creates a new object that is a copy of the original object, but references to the objects within the original object are still shared between the original and the copy. This means that if one of the objects is modified, the change will be reflected in both the original and the copy. Shallow copy can be created using the copy() method or the slicing operator [:].
original_list = [[1, 2, 3], [4, 5, 6]]
copy_list = original_list.copy() # Using copy() method
print(copy_list) # Output: [[1, 2, 3], [4, 5, 6]]
copy_list[0][0] = 100
print(copy_list) # Output: [[100, 2, 3], [4, 5, 6]]
print(original_list) # Output: [[100, 2, 3], [4, 5, 6]]
Deep copy: A deep copy creates a new object that is a copy of the original object, and references to the objects within the original object are also copied into the new object. This means that changes made to the objects within the original object will not be reflected in the new object. Deep copy can be created using the deepcopy() method from the copy module.
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
copy_list = copy.deepcopy(original_list) # Using deepcopy() method
print(copy_list) # Output: [[1, 2, 3], [4, 5, 6]]
copy_list[0][0] = 100
print(copy_list) # Output: [[100, 2, 3], [4, 5, 6]]
print(original_list) # Output: [[1, 2, 3], [4, 5, 6]]
In summary, a shallow copy creates a new object that shares references to objects within the original object, while a deep copy creates a new object with its own copies of the objects within the original object. Shallow copy can be created using the copy() method or the slicing operator [:], while deep copy can be created using the deepcopy() method from the copy module.