Why does this happen?
x = [[]] * 4
x[0].append('x') -> [['x'], ['x'], ['x'], ['x']]
Why does this happen?
x = [[]] * 4
x[0].append('x') -> [['x'], ['x'], ['x'], ['x']]
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)]
[[]] * 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. :)