0

I am trying to create a list which should contain numeric values which I am trying to extract from a dataframe. The following is my code:

list_values = []
j = 0
for i in country_list:        
    list_values[j] = df6['positioning'][i].to_numpy()
    j = j + 1

print(list_values)

When I am trying to just print the values directly without storing them in the list I can do that, but somehow I am not able to store them in the list or a 2d numpy array. What is going wrong?

The following is the error:

IndexError: list assignment index out of range

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
dsnoob27
  • 31
  • 8
  • @viggnah because i need to perform statistical hypothesis test on these values using anova so I thought of storing them in a list and then perform the test – dsnoob27 Jul 09 '22 at 09:07
  • use `list_values.append(df6['positioning'][i].to_numpy())` – Sam Daniel Jul 09 '22 at 09:09

1 Answers1

1

At the beginning, list_values is an empty list and j is 0.

So if you use list_values[j], 0 is an invalid index for an empty list. Therefore you get this error.

You cannot ever grow a list by using index assignment. Index assignment can only replace list items that already exist. In order to grow a list, you can for example use the append method to add an item to the end of the list.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65