django - modifying python list inside iteritems modifies the dict itself -


this question has answer here:

dict = {1:[1,1,1], 2:[2,2,2]} mylist = []  print dict  key, value in dict.iteritems():     mylist.append(value)  item in mylist:     = item[0]+ item[1]     item.append(a)  print dict 

the result of printing dict before operation

{1: [1, 1, 1], 2: [2, 2, 2]} 

while doing after iteritems

{1: [1, 1, 1, 2], 2: [2, 2, 2, 4]} 

why dict modified?

you changing dict's value list , not copy of list

for key, value in dict.iteritems():     mylist.append(value)  id(mylist[0]) 70976616 id(dict[1]) 70976616 

both dict[1] , mylist[0] referencing same memory space change in memory space affect both of them long referencing it

dict[1] [1, 1, 1, 2] mylist[0] [1, 1, 1, 2] 

you use copy ,deep copy etc copy list

or

dict = {1:[1,1,1], 2:[2,2,2]} mylist = []  print dict  key, value in dict.iteritems():     mylist.append(value)  item in mylist:     = item[0]+ item[1]     item=item+[a] # first evaluates rhs creates new memory reference , assigns item  print dict 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -