wtfpython icon indicating copy to clipboard operation
wtfpython copied to clipboard

be careful with deepcopy

Open dugu9sword opened this issue 4 years ago • 0 comments

â–¶ deepcopy cheats

Once you got a list of objects, and you want to make a deep copy of them...

from copy import deepcopy
x=[]
xs = [x] * 2
ys = deepcopy(xs)
ys[0].append(1)  
print(ys)

Output (Python version):

[[1], [1]]

💡 Explanation:

The deepcopy module avoids recursive copy by keeping a memory of copied objects. If the some of the objects are with the same id, the deepcopied objects will share the same, too.

ys = [deepcopy(ele) for ele in xs]
ys[0].append(1) 
print(ys)

Output (Python version):

[[1], []]

dugu9sword avatar Mar 21 '20 00:03 dugu9sword