2

Possible Duplicate:
Python list confusion

I've got one little question about Python lists:

Why does this happen?

x = [[]] * 4
x[0].append('x') -> [['x'], ['x'], ['x'], ['x']]
Community
  • 1
  • 1
cval
  • 6,609
  • 2
  • 17
  • 14
  • 1
    Because you are copying the same list four times. And since in your list you have 4 lists all that point to the same memory space, if you modify one of them, the change will affect all. – rubik Mar 04 '12 at 11:44
  • Also, see [this entry in the Python FAQ](http://docs.python.org/faq/programming.html#how-do-i-create-a-multidimensional-list) – BioGeek Mar 04 '12 at 16:07

1 Answers1

6

the same instance of [] is being duplicated, so when you append to the first one 'x', you actually append it to all - because they are all the same object!

The right way to do it is to explicitly create a new list instance each time:

x = [[] for _ in range(4)]
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
amit
  • 175,853
  • 27
  • 231
  • 333
  • 1
    I added a possible solution to this answer. Hope you don't mind :) – Niklas B. Mar 04 '12 at 11:51
  • To be clear: The instance [] is not being *duplicated*. The expression `[[]] * 4` creates a list with four references to the same instance of []. – alexis Mar 04 '12 at 11:59
  • `[[]] * 4` looked like a nice trick to save some typing, but it bites people in the back afterwards by creating only two real lists and 3 references, which isn't so obvious. I used to do that too, but from now on I'll only use the list comprehension suggested here. Well, for such a small list `[[],[],[],[]]` is also fine. No need to show off using `[[]] * 4`. :) – Frg Mar 04 '12 at 12:22