2

I have a list of empty lists as such:

some_lists = [[]] * 3
[[], [], []]

I want to append an integer to the first sublist:

some_lists[0].append(1)

But it appends the integer 1 to all the sublists and generates:

[[1], [1], [1]]

How do I append elements individually to the sublists?

CK.
  • 312
  • 3
  • 13

1 Answers1

5

You have created a reference to every sublist in the list. Instead, you can use a list comprehension:

some_lists = [[] for i in range(3)]
some_lists[0].append(3)

Output:

[[3], [], []]

 
Ajax1234
  • 69,937
  • 8
  • 61
  • 102