Reputation: 4983
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?
Upvotes: 3
Views: 180
Reputation: 362557
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.
>>> Demo1 = [[], []]
>>> Demo2 = [[]] * 2
>>> print id(Demo1[0]), id(Demo1[1])
33980568 34018800
>>> print id(Demo2[0]), id(Demo2[1])
34169920 34169920
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:
>>> Demo2 = [[] for i in xrange(2)]
>>> Demo2
[[], []]
>>> Demo2[0].append(1)
>>> Demo2
[[1], []]
Upvotes: 4
Reputation: 798546
Demo2
is a list containing two references to the same list.
Demo2 = [[] for x in range(2)]
Upvotes: 2