/    /  Python – Deep Copy

Python Deep Copy

In Python, we create a copy of the already existing objects by using ‘=’ operator with different variable name. By this we have an object with its copy with two different names. If any change is made to one of the object or copy, same change appears in other one too. Sometimes, we need to make original one safe and apply required changes to the copy of original object.

We can create a copy of the object by using copy module. One way of copying objects is Deep copy.

Deep copy is a collection object which is constructed by populating with the copies of the child objects of the original. The copying process of deep copy is recursive unlike shallow copy. In this way of copying an object walks the whole object tree to an independent clone of original object and its children.

A copy of the object is created by using assignment operator ‘ = ’


Python Code

#creating a list 
list1= ["a","b","c","d"]
#creating other list and copying list1
list2=list1
#printing copy list
print(list2)


Output

[‘a’, ‘b’, ‘c’, ‘d’]


Let’s create a copy object by using deep copy


Python Code

import copy
list1= ["a","b","c","d"]
#creating a copy of list1 using deep copy
list2=copy.deepcopy(list1)
#printing copy list
print(list2)
#making changes to list2
list1.append("e")
print("after making changes, list1 is:",list1)
print("after making changes, list2 is:",list2)


Output

[‘a’, ‘b’, ‘c’, ‘d’]

after making changes, list1 is: [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

after making changes, list2 is: [‘a’, ‘b’, ‘c’, ‘d’]