Copy Module in Python – Understanding deepcopy() and shallow copy

In Python, there is a module, which allows you to copy a mutable object so that changes made in the copied list, won’t affect the original list.

This is done by deepcopy(),

image source : www.geeksforgeeks.org

Let it understand by an example :

import copy

# initializing list 1
li1 = [1, 2, [3,5], 4]

# using deepcopy to deep copy
li2 = copy.deepcopy(li1)

# original elements of list
print (“The original elements before deep copying”)
for i in range(0,len(li1)):
print (li1[i],end=” “)

print(“\r”)

# adding and element to new list
li2[2][0] = 7

# Change is reflected in l2
print (“The new list of elements after deep copying “)
for i in range(0,len( li1)):
print (li2[i],end=” “)

print(“\r”)

# Change is NOT reflected in original list
# as it is a deep copy
print (“The original elements after deep copying”)
for i in range(0,len( li1)):
print (li1[i],end=” “)

 

Output would be  :

The original elements before deep copying
1 2 [3, 5] 4
The new list of elements after deep copying
1 2 [7, 5] 4
The original elements after deep copying
1 2 [3, 5] 4

This shows,  that changes made in one list didn’t affect other

So, here what actually happened, deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

 

Whereas in case of Shallow copy or copy(), any changes made to one list will reflect changes in other also.

image source : www.geeksforgeeks.org

 

# importing “copy” for copy operations
import copy

# initializing list 1
li1 = [1, 2, [3,5], 4]

# using copy to shallow copy
li2 = copy.copy(li1)

# original elements of list
print (“The original elements before shallow copying”)
for i in range(0,len(li1)):
print (li1[i],end=” “)

print(“\r”)

# adding and element to new list
li2[2][0] = 7

# checking if change is reflected
print (“The original elements after shallow copying”)
for i in range(0,len( li1)):
print (li1[i],end=” “)

 

Output will be :
The original elements before shallow copying
1 2 [3, 5] 4
The original elements after shallow copying
1 2 [7, 5] 4

Hence, it shows changes made in one list do reflect in other.
Therefore, A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

 

For full documentation please refer  : https://docs.python.org/2/library/copy.html

Copy Module in Python – Understanding deepcopy() and shallow copy
Scroll to top