Net-informations.com
SiteMap  | About    

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

output

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









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.