OK, check out the following codes first:
Demo1 = [[], []]
Demo2 = [[]] * 2
Demo1[0].append(1)
Demo2[0].append(1)
print "Demo1: ", Demo1
print "Demo2: ", Demo2
And here’s the output:
Demo1: [[1], []]
Demo2: [[1], [1]]
I need to create a list whose items are all list as well just like Demo1 and Demo2, of course I used Demo2 in my script and it kept getting into trouble until I found the reason which is what you can see from above codes. So why is this happening? Most of the cases I would use Demo2 to create such list as its length differs each time, but how do I append an item to separate lists within the list without getting into such mess?
For you first question: It is happening because in Demo2 case your list contains two copies of the same object. See for example below where I print the memory locations of those elements, noting that they differ for Demo1 but match for Demo2.
For your second question: you could use a list comprehension like
[[] for i in xrange(n)], in order to be creating a new list n times rather than duplicating the same list n times.Example: