0
dict = {1:[1,1,1], 2:[2,2,2]}
mylist = []

print dict

for key, value in dict.iteritems():
    mylist.append(value)

for item in mylist:
    a = item[0]+ item[1]
    item.append(a)

print dict

the result of printing the dict before the operation is

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

While doing it after the iteritems

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

Why does the dict get modified?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Prabhakar Shanmugam
  • 5,634
  • 6
  • 25
  • 36

1 Answers1

1

You are changing the dict's value list and not the copy of the list

for key, value in dict.iteritems():
    mylist.append(value)

id(mylist[0])
70976616
id(dict[1])
70976616

Both the dict[1] and mylist[0] are referencing to the same memory space so any change in the memory space would affect both of them as long as they are referencing to it

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

You could use copy ,deep copy etc to copy the list

or

dict = {1:[1,1,1], 2:[2,2,2]}
mylist = []

print dict

for key, value in dict.iteritems():
    mylist.append(value)

for item in mylist:
    a = item[0]+ item[1]
    item=item+[a] # this first evaluates the RHS creates a new memory reference and assigns it to item

print dict
The6thSense
  • 8,103
  • 8
  • 31
  • 65