1

Consider this example:

>>> result = [[]] * 8
>>> result
[[], [], [], [], [], [], [], []]
>>> result[0]
[]
>>> result[0].append("foo")
>>> result  # wtf? expected result: [['foo'], [], [], [], [], [], [], []]
[['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo'], ['foo']]

I'm terribly confused by this. Maybe I don't understand how append is expected to be used. How would I append to the ith nested listed inside a list?

David Chouinard
  • 6,466
  • 8
  • 43
  • 61

1 Answers1

5

That's because, by doing this:

result = [[]] * 8

you make 8 copies of the same list. Your code should be:

>>> result = [[] for _ in xrange(8)]
>>> result
[[], [], [], [], [], [], [], []]
>>> result[0]
[]
>>> result[0].append("foo")
>>> result
[['foo'], [], [], [], [], [], [], []]
>>>

As a proof, consider this:

>>> lst = [[]] * 2
>>> lst
[[], []]
>>> id(lst[0])
28406048
>>> id(lst[1])
28406048
>>>

Notice that the id's of the lists are the same where as here:

>>> lst = [[] for _ in xrange(2)]
>>> lst
[[], []]
>>> id(lst[0])
28408408
>>> id(lst[1])
28418096
>>>

they are different.