This is my code:
a = [[]] * 10
a[0].append(1)
print a # Outputs [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
How can I get a to output
[[1], [], [], [], [], [], [], [], [], []]
?
asked Feb 19, 2012 at 20:15
Randomblue
117k151 gold badges363 silver badges560 bronze badges
-
1docs.python.org/faq/…Praveen Gollakota– Praveen Gollakota2012年02月19日 20:17:38 +00:00Commented Feb 19, 2012 at 20:17
-
1Initialise a list to a specific length in PythonPaolo Moretti– Paolo Moretti2012年02月19日 20:20:47 +00:00Commented Feb 19, 2012 at 20:20
-
1@PaoloMoretti: That's not the same question, although there are countless duplicates on SO.Wooble– Wooble2012年02月19日 20:39:02 +00:00Commented Feb 19, 2012 at 20:39
-
@Wooble No, it's not, but the answer from Alex Martelli also answers this question.Paolo Moretti– Paolo Moretti2012年02月19日 20:45:49 +00:00Commented Feb 19, 2012 at 20:45
3 Answers 3
Try
a=[[] for i in xrange(10)]
In your code you're adding the same list 10 times. The following output should clarify this:
>>> a=[[]] * 5
>>> for i in a: print id(i)
...
155302636
155302636
155302636
155302636
155302636
>>> a=[[] for i in xrange(5)]
>>> for i in a: print id(i)
...
155302668
155302732
155302924
155303020
155303052
As you can see, in the first example a contains 5 times a reference to the same array object, in the second example it contains references to 5 different array objects.
answered Feb 19, 2012 at 20:17
hochl
13.2k10 gold badges59 silver badges92 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Your current code creates an array containing the same array ten times.
Use [[] for i in xrange(10)] so you actually create separate arrays.
answered Feb 19, 2012 at 20:17
ThiefMaster
320k85 gold badges608 silver badges648 bronze badges
Comments
Try this:
>>> a = [[] for i in range(10)]
>>> a[0].append(1)
>>> a
[[1], [], [], [], [], [], [], [], [], []]
answered Feb 19, 2012 at 20:17
grifaton
4,0564 gold badges32 silver badges42 bronze badges
Comments
lang-py