This list is initialized to be a list of 10 empty lists, and if I add to one sublist, as part of a loop, that changes all sublists:
x=[[]]*10
x[4]+=[4]
x
[[4], [4], [4], [4], [4], [4], [4], [4], [4], [4]]
If I use =
then it works differently:
x=[[]]*10
x[4]=[4]
x
[[], [], [], [], [4], [], [], [], [], []]
x[4]+=[8]
x
[[], [], [], [], [4, 8], [], [], [], [], []]
x[2]+=[1]
x
[[1], [1], [1], [1], [4, 8], [1], [1], [1], [1], [1]]
It looks as if [[]]*10 creates 1 empty list and 10 references to the same empty list. Whereas ['']*10 actually creates 10 different '':
x=['']*10
x
['', '', '', '', '', '', '', '', '', '']
x[4]+='aa'
x
['', '', '', '', 'aa', '', '', '', '', '']
Using [[] for i in range(10)]
works. However, I'd appreciate a good explanation for this.