django - modifying python list inside iteritems modifies the dict itself -
this question has answer here:
- how clone or copy list? 14 answers
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
Post a Comment