Does Python's copy.deepcopy really copy everything? -
Does Python's copy.deepcopy really copy everything? -
this question has reply here:
what difference between shallow copy, deepcopy , normal assignment operation? 3 answersi under impression deepcopy copied recursively downwards tree, came upon situation seemed go against believed.
>>> item = "hello" >>> a["hello"] = item >>> b = copy.deepcopy(a) >>> id(a) 31995776 >>> id(b) 32733616 # expected >>> id(a["hello"]) 140651836041376 >>> id(b["hello"]) 140651836041376 # did not expect
the id of , b different, expected, internal item still same object. deepcopy re-create depth? or specific way python stores strings? (i got similar result integers well)
deepcopy
needs create copies of mutable objects, lists , dictionaries. strings , integers immutable; can't changed in-place, there's no need explicitly create copy, , reference same object inserted instead.
here quick demo, showing difference between lists (mutable) , tuples (immutable):
>>> import re-create >>> l = [[1, 2], (3, 4)] >>> l2 = copy.deepcopy(l) >>> l2[0] l[0] false # created new list >>> l2[1] l[1] true # didn't create new tuple
python python-2.7
Comments
Post a Comment