shallow copy vs. deep copy in python



Object assignment does not copy object, it gets shared. All names point to same object.
For mutable object types, modifying object using one name, reflects changes when accessed with other name.
Example :
>>> l=[1,2,3]
>>> l2 = l
>>> l2.pop(0)
1
>>> l2
[2, 3]
>>> l
[2, 3]

A copy module overcomes above problem by providing copy() and deepcopy(). copy() creates a copy of an object, creating a separate entity.
Example of shallow copy copy():
>>> import copy
>>> copied_l = copy.copy(l)  # performs shallow copy
>>> copied_l.pop(0)
2
>>> copied_l
[3]
>>> l
[2, 3]

copy() does not perform recursive copy of object. It fails for compound object types.
Example program for shallow copy problems:
>>> l
[[1, 2, 3], ['a', 'b', 'c']]
>>> s_list=copy.copy(l)       # performs shallow copy

>>> s_list
[[1, 2, 3], ['a', 'b', 'c']]
>>> s_list[0].pop(0)
1
>>> s_list
[[2, 3], ['a', 'b', 'c']]
>>> l
[[2, 3], ['a', 'b', 'c']]
          # problem of shallow copy on compund object types

To overcome this problem, copy module provides deepcopy(). deepcopy() creates and returns deep copy of compound object (object containing other objects)
Example for deep copy deepcopy():
>>> l
[[1, 2, 3], ['a', 'b', 'c']]
>>> deep_l = copy.deepcopy(l)
>>> deep_l
[[1, 2, 3], ['a', 'b', 'c']]
>>> deep_l[0].pop(0)
1
>>> deep_l
[[2, 3], ['a', 'b', 'c']]
>>> l
[[1, 2, 3], ['a', 'b', 'c']]

 

No comments:

Post a Comment