Julien REINAULD
Julien REINAULD

Reputation: 639

weird behaviour with list of dictionaries in python

Here is a simple code that performs operations on lists:

>>> a = [0] * 5
>>> a
[0, 0, 0, 0, 0]
>>> a[0] = 5
>>> a
[5, 0, 0, 0, 0]
>>> 

For now, nothing abnormal.

Now, I try to do the same with a list of dictionaries instead of a list of integers:

>>> a = [{}] * 5
>>> a
[{}, {}, {}, {}, {}]
>>> a[0]['b'] = 4
>>> a
[{'b': 4}, {'b': 4}, {'b': 4}, {'b': 4}, {'b': 4}]
>>> 

I don't understand why all elements of my list are modified...

Can anyone tell me why? And also provide a workaround?

Upvotes: 2

Views: 191

Answers (2)

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

Try this,

a = map([].append, {} for i in xrange(3))

Upvotes: 0

eumiro
eumiro

Reputation: 212835

This is not weird.


Workaround:

a = [{} for i in xrange(5)]

[…] * 5 creates one and a list of five pointers to this .

0 is an immutable integer. You cannot modify it, you can just replace it with another integer (such as a[0] = 5). Then it is a different integer.

{} is a mutable dictionary. You are modifying it: a[0]['b'] = 4. It is always the same dictionary.

Upvotes: 9

Related Questions