1

I have a simple scenario where Python (3.7, tested also 3.5) does not seem to behave as I expect. putting it simply:

a = [{"c":1, "d":2}]
a
[{'c': 1, 'd': 2}]
b = a + a
b
[{'c': 1, 'd': 2}, {'c': 1, 'd': 2}]
b[0]
{'c': 1, 'd': 2}
b[0]['c'] = 3
b
[{'c': 3, 'd': 2}, {'c': 3, 'd': 2}]

Changing the value of an entry in the first dictionary in b, also updates the corresponding entry in the 2nd dictionary. I have tried b = a.copy() + a.copy() but got the same result. Does anyone know a way around it?

1 Answer 1

0

You should use deepcopy

copy returns only a shallow copy so since your dictionary is inside the list copy will create new list but the dictionary inside the list will still reference the same dictionary.

shallow copy would work if you had this case:

a = {"c":1, "d":2}
b = [a.copy(), a.copy()] 

But in your case you need to use deepcopy

from copy import deepcopy

b = deepcopy(a) + deepcopy(a)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.