Reputation: 87
I recently came across a strange observation while creating list of dictionaries by appending dictionaries to a list.
Below is my code:
a = []
for i in range(5):
m = {'a':'apple'}
a.append(m)
m['b'] = 'ball'
for i in a:
print(i)
I expected that the list a
will only contain 'a': 'apple'
as the key b
is defined after the append statement.
Suprisingly, below is the output I obtained:
{'a': 'apple', 'b': 'ball'}
{'a': 'apple', 'b': 'ball'}
{'a': 'apple', 'b': 'ball'}
{'a': 'apple', 'b': 'ball'}
{'a': 'apple', 'b': 'ball'}
Why does this happen? Thanks in advance!
Upvotes: 3
Views: 72
Reputation: 1377
That's because 2 things in python:
m
is a dict, even it's been appended to object a
. Its value can still be updated after that. This will affect the value been appended to a
too.a.append(m)
, you are not passing m's value to append()
but m's reference. So when you update m's value, a's value will be updated as well.I suggest you can study the mutable and immutable objects in python further.
Upvotes: 2