Shallow and deep copy operations
copy.
copy
(x)- Return a shallow copy of x.
copy.
deepcopy
(x)- Return a deep copy of x.A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.A 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.
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']]
No comments:
Post a Comment