Python : how to append new elements in a list of list?

You must do

a = [[] for i in xrange(3)]

not

a = [[]]*3

Now it works:

$ cat /tmp/3.py
a = [[] for i in xrange(3)]

print str(a)

a[0].append(1)
a[1].append(2)
a[2].append(3)

print str(a[0])
print str(a[1])
print str(a[2])

$ python /tmp/3.py
[[], [], []]
[1]
[2]
[3]

When you do something like a = [[]]*3 you get the same list [] three times in a list. The same means that when you change one of them you change all of them (because there is only one list that is referenced three times).

You need to create three independent lists to circumvent this problem. And you do that with a list comprehension. You construct here a list that consists of independent empty lists []. New empty list will be created for each iteration over xrange(3) (the difference between range and xrange is not so important in this case; but xrange is a little bit better because it does not produce the full list of numbers and just returns an iterator object instead).

Leave a Comment