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?
-
I repeat the print "Demo2: ", Demo2 a couple of times and I found that online first line doesn't work, subsequent line is working, weird huhdrhanlau– drhanlau2011年12月22日 06:13:44 +00:00Commented Dec 22, 2011 at 6:13
-
Should be in the next weekly newsletter :)Kirill– Kirill2011年12月22日 06:14:18 +00:00Commented Dec 22, 2011 at 6:14
2 Answers 2
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], []]
1 Comment
Demo2 = [[]] * 2
.Demo2
is a list containing two references to the same list.
Demo2 = [[] for x in range(2)]