1

I have been using Python for some years now but just noticed a very confusing thing.

a=[[]]*3
a[0].append(3)

and

a=[[] for i in range(3)]
a[0].append(3)

do not have the same effect even though the type (list) is the same. The first yields a=[[3], [3], [3]], the second a=[[3],[],[]] (as expected).

Does anybody have an explanation?

user3117090
  • 143
  • 6
  • 3
    so many duplicates ... – wim Dec 18 '13 at 22:34
  • 1
    @jonrsharpe That is so close to an exact duplicate it just blew my mind! – SethMMorton Dec 18 '13 at 22:37
  • 3
    And the question is _about_ duplicates. It's a metaduplicate? – John La Rooy Dec 18 '13 at 22:50
  • @wim, perhaps but how do you search for them? – Mark Ransom Dec 18 '13 at 23:12
  • In the spirit of the duplicates, here are 3 ... http://stackoverflow.com/questions/17702937/generating-sublists-using-multiplication-unexpected-behavior http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of-lists http://stackoverflow.com/questions/13058458/python-list-index – wim Dec 18 '13 at 23:46

1 Answers1

10

[[]]*3 creates a list with three references to the same list object:

>>> lst = [[]]*3
>>> # The object ids of the lists in 'lst' are the same
>>> id(lst[0])
25130048
>>> id(lst[1])
25130048
>>> id(lst[2])
25130048
>>>

[[] for i in range(3)] creates a list with three unique list objects:

>>> lst = [[] for i in range(3)]
>>> # The object ids of the lists in 'lst' are different
>>> id(lst[0])
25131768
>>> id(lst[1])
25130008
>>> id(lst[2])
25116064
>>>