I defined a new list like A=[[],]*10
. I am trying to initialize a list of length 10 where each element is a empty list.
But when I do something like A[0].append(["abc",])
, the ["abc",]
value is appended to each element of A
, but I only want it to be appended to A[0]
. Why does this happen?
You are creating a list with 10 references to the same empty list.
You should use a list comprehension instead:
A = [[] for _ in range(10)]
In a list comprehension, you create a new list for every iteration through the loop. If you are using python 2, you should use xrange
instead of range
(although with only 10 elements that won't make much difference).