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
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.
Try this,
a = map([].append, {} for i in xrange(3))