2

Why does this happen?

x = [[]] * 4
x[0].append('x') -> [['x'], ['x'], ['x'], ['x']]
2
  • 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. Commented Mar 4, 2012 at 11:44
  • Also, see this entry in the Python FAQ Commented Mar 4, 2012 at 16:07

1 Answer 1

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

I added a possible solution to this answer. Hope you don't mind :)
To be clear: The instance [] is not being duplicated. The expression [[]] * 4 creates a list with four references to the same instance of [].
[[]] * 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. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.