+ 1
dict={1:2,3:4} d=dict d[1]=9 print (dict) dict is unchanged after its declaration. Why the output of this code is {1:9,3:4}
3 Respuestas
+ 5
d and dict are a kind of pointer to the same memory space.
+ 3
What you did in your code is a so called shallow copy. Both dict and d have the same object id, so they are referencing the same object.
To get 2 independent objects you can use copy() when you create d in this case.
d=dict.copy()
[Edited]:
If your source list is a compound list (means that it contains e.g. lists), you have to use deep copy. So the code has to be:
from copy import deepcopy
a = [1,2,3,[11,9]]
b = deepcopy(a)
In this case b will be independent from a, and also [11,9] will be independent from sub list in a.
+ 1
Thanks all