The following code surprised me.
alist = [[]] * 4
alist[0].append(100)
I expected that alist would be
[[100],[],[],[]]
but it turned out to be
[[100],[100],[100],[100]]
Does anyone know why python works that way? thank you.
The following code surprised me.
alist = [[]] * 4
alist[0].append(100)
I expected that alist would be
[[100],[],[],[]]
but it turned out to be
[[100],[100],[100],[100]]
Does anyone know why python works that way? thank you.
on this line alist = [[]] * 4
you are creating one inner list and 4 references to the same list, to fix this you can use:
alist = [[] for _ in range(4)]
alist1 = [[] for _ in range(4)]
alist1[0] = 100
print(alist1)