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']]
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']]
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)]