-2

What is the reason for this output?

Here is an example:

list_ = [{'status': True}]
print(list_)

for dict_ in list_:    
    dict_['status'] = False 

print(dict_)
print(list_)

Out:

[{'status': True}]
{'status': False}
[{'status': False}]  # Why list_ changed? I changed only the dict_!

Why list_ changed? I changed only the dict_

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
  • if you want a `deepcopy`: https://stackoverflow.com/a/17873397/937153 – Unni May 02 '19 at 14:40
  • 1
    When you loop over the elements of the list, you're accessing pointers to those objects. Because python works 'by reference', when you change the value of one item, you're modifying the original list. This is why it is not recommended to modify the elements of a list while iterating over it. – gergf May 02 '19 at 14:46

2 Answers2

3

List and dict are mutable objects, which basically means that they point to the same in-memory object.

olinox14
  • 6,177
  • 2
  • 22
  • 39
0

You altered the the dictionary, which the list contains. So you altered the value at its memory address.

Alec
  • 8,529
  • 8
  • 37
  • 63