Home > Blockchain >  IndexError: list index out of range due to empty list within list
IndexError: list index out of range due to empty list within list

Time:03-26

I have a list of a group of lists inside and I'm trying to create a dictionary by assigning each element in a group as a value to a key. However, one of these groups is just an empty list. I tried to use the filter() function to eliminate that empty list and I also tried using the remove() function, however, none of those work. It results in the following error:

my_dict = {'letter': g[0], 'my_arr': g[1], 'second_letter_conf': g[2]}
IndexError: list index out of range

This is what I have tried:

import numpy as np

my_list = [['A', np.array([4, 2, 1, 6]), [['B', 5]]], [' '], ['C', np.array([8, 5, 5, 9]), [['D', 3]]]]
# my_list = list(filter(None, my_list)) # does not work

for g in my_list:
    # if g == [' ']:
    #     my_list.remove(g) # does not work
    my_dict = {'letter': g[0], 'my_arr': g[1], 'second_letter_conf': g[2]}

Where am I going wrong? How do I eliminate that one empty list from my_list?

CodePudding user response:

You can't mutate a list as you iterate it safely. But you can just skip the element and move to the next; you were quite close really:

for g in my_list:
    if g == [' ']:  # I might suggest instead doing if len(g) != 3:
                    # if any length 3thing is good, and other lengths should be discarded
        continue  # Skip this element, go to next
    my_dict = {'letter': g[0], 'my_arr': g[1], 'second_letter_conf': g[2]}

If you need to exclude it from my_list (you'll be using it over and over and don't want to have it there in the future), a quick pre-filter with a listcomp is the simplest solution (and if it lets you assume length three data for what remains, it will allow you to unpack for cleaner/more-self-documenting code in subsequent use):

my_list = [x for x in my_list if x != [' ']]
for let, arr, let2_conf in my_list:
    my_dict = {'letter': let, 'my_arr': arr, 'second_letter_conf': let2_conf}
  • Related