In [33]: x=[[]]*6
In [34]: x
Out[34]: [[], [], [], [], [], []]
In [35]: x[0]
Out[35]: []
In [36]: x[0].append(1)
In [37]: x
Out[37]: [[1], [1], [1], [1], [1], [1]]
I just append 1 to x[0], but why do all lists in the list x change?
In [33]: x=[[]]*6
In [34]: x
Out[34]: [[], [], [], [], [], []]
In [35]: x[0]
Out[35]: []
In [36]: x[0].append(1)
In [37]: x
Out[37]: [[1], [1], [1], [1], [1], [1]]
I just append 1 to x[0], but why do all lists in the list x change?
This happens because x
is a list of references to the same inner list.
To create a list of 6 different empty lists, you can use list comprehension:
a = [[] for _ in range(6)]