Python Shallow and Deep Copy

When creating copies of arrays or objects one can make a deep copy or a shallow copy . Shallow copying is creating a new object and then copying the non static fields from the current object to the new object. If the field is a value type , a bit by bit copy of the field is performed. If the field is a reference type , the reference is copied but the referred object is not, therefore the original object and its clone refer to the same object. While Deep copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, a bit by bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed. example
import copy color1 = ['Red', 'Blue'] color2 = ['White','Black'] color3 = [color1 , color2] # normal copy color4 = color3 print (id(color3) == id(color4)) # True - color3 is the same object as color4 print (id(color3[0]) == id(color4[0])) # True - color4[0] is the same object as color3[0] # shallow copy color4 = copy.copy(color3) print (id(color3) == id(color4)) # False - color4 is now a new object print (id(color3[0]) == id(color4[0])) # True - The new variable refers to the original variable. # deep copy color4 = copy.deepcopy(color3) print (id(color3) == id(color4)) # False - color4 is now a new object print (id(color3[0]) == id(color4[0])) # False - color4[0] is now a new object
output
True True False True False False
Explanation: color4 = color3

Here using normal assignment operating to copy (color4 = color3)

print (id(color3) == id(color4))

output is True because color3 is the same object as color4

print (id(color3[0]) == id(color4[0]))

output is True because color4[0] is the same object as color3[0]

In the next line we perform Shallow Copy

color4 = copy.copy(color3)

A shallow copy constructs a new compound object and then inserts references into it to the objects found in the original.

print (id(color3) == id(color4))

output is False because color4 is now a new object

print (id(color3[0]) == id(color4[0]))

output is True because color4[0] is the same object as color3[0]

In the next line we perform Deep Copy

color4 = copy.deepcopy(color3)

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

print (id(color3) == id(color4))

output is False because color4 is now a new object

print (id(color3[0]) == id(color4[0]))

output is False because color4[0] is now a new object