Here is a very simple program:
a = [[]]*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])
Here is the output I was expecting:
[[], [], []]
[1]
[2]
[3]
But instead I get this :
[[], [], []]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
There is really something I do not get here !
You must do
not
Now it works:
When you do something like
a = [[]]*3you 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 overxrange(3)(the difference betweenrangeandxrangeis not so important in this case; butxrangeis a little bit better because it does not produce the full list of numbers and just returns an iterator object instead).