0

I want to add an element in a nested list

my_list = [[0]]*10
x = int(input())   
my_list[x].append(x)

print(my_list)

The output I am expecting if x=1 :

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

But this is what I am getting:

[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
xb2107
  • 47
  • 4

1 Answers1

1

You instantiate my_list with ten times the same list pointer [0]. So if you append to the list, this will be reflected in all ten elements in the list. Instead, create your list with

my_list = [[0] for _ in range(10)]

This will make 10 seperate lists.

gustavolq
  • 408
  • 3
  • 10
drmaettu
  • 71
  • 4