I am creating a list of lists and I want to add items to separate lists, but when I try to add one of the lists ( a[0].append(2) ), the item is added to all lists.
a = [] b = [1] a.append(b) a.append(b) a[0].append(2) a[1].append(3) print(a)
Gives: [[1, 2, 3], [1, 2, 3]]
While I would expect: [[1, 2], [1, 3]]
Changing the way you create the original list of lists, making b float instead of a list and placing the brackets inside .append() , will give me the desired result:
a = [] b = 1 a.append([b]) a.append([b]) a[0].append(2) a[1].append(3) print(a)
Gives: [[1, 2], [1, 3]]
But why? It is not interesting that the result should be different. I know that this is due to the fact that there are several links to the same list , but I do not see where this is happening.
litturt
source share