Friday, 1 September 2017

Pthon deep copy

Shallow and deep copy operations
copy.copy(x)
Return a shallow copy of x.
copy.deepcopy(x)
Return a deep copy of x.

shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

This behaviour is depicted in the following diagram: it is a shallow copy
 lst1 = ['a','b',['ab','ba']]
>>> lst2 = lst1[:]
>>> lst2[0] = 'c'
>>> lst2[2][1] = 'd'
>>> print(lst1)
['a', 'b', ['ab', 'd']]


The following diagram depicts what happens, if one of the elements of a sublist will be changed: Both the content of lst1 and lst2 are changed. 

Copying lists containing sublists








from copy import deepcopy

lst1 = ['a','b',['ab','ba']]

lst2 = deepcopy(lst1)

lst2[2][1] = "d"
lst2[0] = "c";

print lst2
print lst1
If we save this script under the name of deep_copy.py and if we call the script with "python deep_copy.py", we will receive the following output:
$ python deep_copy.py 
['c', 'b', ['ab', 'd']]
['a', 'b', ['ab', 'ba']]
Copy a list with Deep-Copy


No comments:

Post a Comment