Deep Copy in Python |
in Python assignment statements create references to the same object rather than
copying it the copy module can be used to create shallow (copy.copy()) and deep (copy.deepcopy()) copies a deep copy creates a new compound/collection object then recursively populates it with copies of the child objects found in the original any changes made to a copy of the object do not reflect in the original object implemented using the copy.deepcopy() function import copy a = [[1, 2, 3], [4, 5, 6]] # Creating a deep copy of the nested list 'a' b = copy.deepcopy(a) # Modifying an element in the deep-copied list b[0][0] = 99 print(a) # output [[1, 2, 3], [4, 5, 6]] print(b) # output [[99, 2, 3], [4, 5, 6]] |
Shallow Copy in Python |
a shallow copy creates a new object but retains references to the objects contained
within the original only copies the top-level structure without duplicating nested elements changes made to a copy of an object do reflect in the original object implemented using the copy.copy() function import copy a = [[1, 2, 3], [4, 5, 6]] # Creating a shallow copy of the nested list 'a' b = copy.copy(a) # Modifying an element in the shallow-copied list b[0][0] = 99 print(a) # output [[99, 2, 3], [4, 5, 6]] print(b) # output [[99, 2, 3], [4, 5, 6]] |