Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting an error on trying to assign arrays to each element of a list?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

IndexError: list assignment index out of range

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading