Difference between Shallow copy and Deep copy in Python

First of all, we will discuss about cloning concept in python.

See the following example.If we print both lists, we get the same output.

list1 = [ 1,2,3,4]

list2 = list1

print(list1) # 1 2 3 4


print(list2) # 1 2 3 4

list1[0] = 9

I have changed the 0th index of list1. Now, If we print both lists,can you guess what the output will be?

print(list1) # 9 2 3 4


print(list2) # 9 2 3 4

Changes of list1 reflect in list2. Because those point to the same object.To check whether those list point same object or not, see the following code.

print(id(list1) == id(list2)) # True

Those have the same memory address.Now observe the following example.

list1 = [ 1,2,3,4]

list2 = list1.copy()

print(list1) # 1 2 3 4

print(list2) # 1 2 3 4

list1[0] = 9

print(list1) # 9 2 3 4

?print(list2) # 1 2 3 4



Now they will give different output because those point two different object by copy() function.This is called cloning concept in python.

Difference between shallow copy and deep copy 

Shallow copy

Before describing shallow copy observe the following code. copy.copy() is shallow copy.

import copy 


# example 1

l1 = [1,2,3]

l2 = copy.copy(l1)



print(l1) # 1 2 3 

print(l2) # 1 2 3



l1[0]=100


print(l1) # 100 2 3

print(l2) # 1 2 3



print(id(l1) == id(l2))  # False


# example 2 

import copy

l1 = [1,[2,8,9],3]

l2 = copy.copy(l1)



print(l1) # [1, [2, 8, 9], 3]  

print(l2) # [1, [2, 8, 9], 3] 



l1[0] = 100

l1[1][0]= 66


print(l1) # [100, [66, 8, 9], 3] 

print(l2) # [1, [66, 8, 9], 3]  



print(id(l1) == id(l2)) #False

In both example l1 and l2 both point to two different object.So, changes in l1[0] does not reflect in l2[0].

But in example 2,when l1 contains mutable object and changes in mutable object of l1 alse reflects in l2 object.

So we can say in shallow copy,

If the original object contains any references to mutual objects, just duplicate reference variables will be created pointing to old contained objects, but not duplicate creation.

Deep Copy

Before describing deep copy observe the following code. copy.deepcopy() is deep copy.

import copy 


# example 1

l1 = [1,2,3]

l2 = copy.deepcopy(l1)


print(l1) # 1 2 3 

print(l2) # 1 2 3


l1[0]=100


print(l1) # 100 2 3

print(l2) # 1 2 3


print(id(l1) == id(l2)) #False



# example 2 

l1 = [1,[2,8,9],3]

l2 = copy.deepcopy(l1)


print(l1) # [1, [2, 8, 9], 3]  

print(l2) # [1, [2, 8, 9], 3] 


l1[0] = 100

l1[1][0]= 66


print(l1) # [100, [66, 8, 9], 3] 

print(l2) # [1, [2, 8, 9], 3]  


print(id(l1) == id(l2)) # False


In deep copy,

L1 and l2 are two seperate objects and any changes in l1 does not reflect on l2 although l1 contains mutable object.

*** l2 = l1.copy() and l2 = copy.deepcopy() behave same 

要查看或添加评论,请登录

Mahmudul Hasan的更多文章

社区洞察

其他会员也浏览了