Skip to content Skip to sidebar Skip to footer

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] >>>

Solution 1:

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.

Solution 2:

Try this,

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

Post a Comment for "Weird Behaviour With List Of Dictionaries In Python"