0

I have a list of list and I would like to add an element inside only one of the list but it is added everywhere. You can find my code bellow

repartition_labels = [[]]*3
repartition_labels[2].append(2)

The result I have is

[[2], [2], [2]]

and I would like to have the result

[[], [], [2]]

I already tried to function insert and extend but it didn't solve the problem

codelch
  • 33
  • 7

2 Answers2

2

With repartition_labels = [[]]*3, you are generating a list which contains 3 references to the same object.

When you change that object, all references will show the (same) updated object.

goodvibration
  • 5,980
  • 4
  • 28
  • 61
1

You have to do this:

repartition_labels = [[] for _ in range(0, 3)]
repartition_labels[2].append(2)

Output:

[[], [], [2]]

The reason your code is not working as expected, is because by [[]] * 3 you're creating three references to the same list.

baduker
  • 19,152
  • 9
  • 33
  • 56