Skip to content

be careful with deepcopy #191

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dugu9sword opened this issue Mar 21, 2020 · 0 comments
Open

be careful with deepcopy #191

dugu9sword opened this issue Mar 21, 2020 · 0 comments

Comments

@dugu9sword
Copy link

▶ 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 dugu9sword changed the title be deepcopy be careful with deepcopy Mar 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants