+ 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}

1st Nov 2019, 7:02 AM
saqibcheema
saqibcheema - avatar
3 odpowiedzi
+ 5
d and dict are a kind of pointer to the same memory space.
1st Nov 2019, 7:05 AM
Oma Falk
Oma Falk - avatar
+ 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.
1st Nov 2019, 7:45 AM
Lothar
Lothar - avatar
+ 1
Thanks all
1st Nov 2019, 8:57 AM
saqibcheema
saqibcheema - avatar