Shallow Copy Vs Deep Copy

Consider a dictionary:

animals= {

"lion" : "scary",

"elephant" : "big",

"teddy" : "cuddly",

}

things=animals

animals["teddy"]="toy"

print(things["teddy"])

#Output:

toy

In the above example when we did things=animals we made one more dictionary things but it points to same dictionary animals so they both are the same dictionary and animals as well as things pointing to same dictionary i.e

{

"lion" : "scary",

"elephant" : "big",

"teddy" : "toy",

}

Therefore to create a separate dictionary we have shallow copy

What is a shallow copy ?

shallow copy creates a new object, but does not create copies of the nested objects within the original object. Instead, it inserts references to the same objects into the new object. This means that changes to the nested objects in the copied object will reflect in the original object and vice versa. To use it we will import a copy module and use copy() function.

Let us learn by example:

import copy

animals= {

"lion" : ["scary" ,"big" ,"cat"] ,

"elephant" : ["big", "grey" ,"wrinkled"] ,

"teddy" : ["cuddly", "stuffed" ],

}

things=animals.copy()

print(things["teddy"])

print()

things["teddy"].append("toy")

print(things["teddy"])

print(animals["teddy"])

#Output

['cuddly' , 'stuffed']

['cuddly' , 'stuffed' , 'toy']

['cuddly' , 'stuffed' , 'toy']

Here in the above example though two different dictionaries are made but the value inside this dictionary i.e list is stored as reference in key-value pair . Hence any change in nested object i.e one value will be reflected in the other

Note: With immutable values no issue as they cannot be changed but with mutable values references are there so change in either one will be reflected in other.

Why DeepCopy ?

A deep copy creates a new compound object before inserting copies of the items found in the original into it in a recursive manner. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In the case of deep copy, a copy of the object is copied into another object. It means that any changes made to a copy of the object do not reflect in the original object. 

That means it creates two complete separate objects so any change in one of any kind won,t be reflected in other. To create a deepcopy python has a deep copy function in copy module.

import copy

animals= {

"lion" : ["scary" ,"big" ,"cat"] ,

"elephant" : ["big", "grey" ,"wrinkled"] ,

"teddy" : ["cuddly", "stuffed" ],

}

things=copy.deepcopy(animals)

print()

things["teddy"].append("toy")

print(things["teddy"])

print(animals["teddy"])

#Output

['cuddly', 'stuffed', 'toy']

['cuddly', 'stuffed']

Leave a Reply

Your email address will not be published. Required fields are marked *