"string index out of range" error cleaning list?

Hi folks!

In working on a project, I came across this error I don’t understand.

Basically, I’m writing a function that’s meant to talk a list of lists (list) and an empty list (new_list) as arguments, and then look at the 5th column (index 4) for each row, assess whether the characters in the string are numeric, and then if they are, append the entire row to new_list.

I realize this isn’t the most efficient way of doing this anyway (still learning numpy, pandas, and vectorization), but I still don’t understand the error below, “string index out of range”.

Shouldn’t it be a list index? I know that list has more than 5 columns, so I’m confused about:

  1. what it means by string index
  2. why it’s looking at that instead of index 4 in list

and also possibly whether this function would work correctly otherwise.

Thoughts?

def clean_comments(list, new_list):
    for row in list:
        comment = row[4]
        if comment.isnumeric == True:
            new_list.append(row)
<ipython-input-15-bcd2ead7d47c> in clean_comments(list)
      3 def clean_comments(list):
      4     for row in list:
----> 5         comment = row[4]
      6         if comment.isnumeric == True:
      7             clean_ask_list.append(row)

IndexError: string index out of range
2 Likes

Hi @charlie! It’s hard to tell without a more full code sample, but is it possible that the input list to the function isn’t a list of lists, but a list of strings instead?

It appears to me that row is a string in the traceback you posted, and that it’s a string that is less than 5 characters long.

Printing out row and type(row) in the first line of the loop can help you debug.

Also, you need to call the isnumeric method by adding parentheses, like isnumeric().

1 Like

thanks, @vik, I think that was it! So used to working with lists of lists that I just dove in and treated it like one.