Rohith
Rohith

Reputation: 87

Appending Dictionaries to a Python List: Strange Result?

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

Answers (1)

nngeek
nngeek

Reputation: 1377

That's because 2 things in python:

  1. dict in python is a mutable object. In your code, the 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.
  2. function parameter is always assigned by Reference in python. In code 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

Related Questions