wtfpython
wtfpython copied to clipboard
be careful with deepcopy
â–¶ 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], []]