I create 3 empty list nested in a list, and index to append to the first one, but it results in all the list:
In [1]:
...: a = [[]] * 3
...: a[0].append(3)
...: print(a)
Out [1]:
[[3], [3], [3]]
My expect output is:
[[3], [], []]
But if I do this:
In [2]:
...: b = []
...: for i in range(3):
...: b.append([])
...: b[0].append(3)
...: print(b)
Out [2]:
[[3], [], []]
Then I got my expect output
Thanks
CodePudding user response:
Because in the first case, you are trying to access the same object (the object and its refernces).
But in the second case, list a
has totally different -new- objects.