3

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?

asked Dec 22, 2011 at 6:06
2
  • 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 huh Commented Dec 22, 2011 at 6:13
  • Should be in the next weekly newsletter :) Commented Dec 22, 2011 at 6:14

2 Answers 2

4

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], []]
answered Dec 22, 2011 at 6:10

1 Comment

Thanks mate, problem solved. Although still don't understand why it's designed to be like this. To me, it does not make sense creating duplicate stuff using Demo2 = [[]] * 2.
2

Demo2 is a list containing two references to the same list.

Demo2 = [[] for x in range(2)]
answered Dec 22, 2011 at 6:10

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.