3

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], [], [], [], [], [], [], [], [], []]

?

Randomblue
  • 112,777
  • 145
  • 353
  • 547

3 Answers3

12

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.

hochl
  • 12,524
  • 10
  • 53
  • 87
3

Your current code creates an array containing the same array ten times.

Use [[] for i in xrange(10)] so you actually create separate arrays.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

Try this:

>>> a = [[] for i in range(10)]
>>> a[0].append(1)
>>> a
[[1], [], [], [], [], [], [], [], [], []]
grifaton
  • 3,986
  • 4
  • 30
  • 42