"IndexError: list index out of range" at Index 0

Question:

I am trying to reorganize some data from a csv file using the csv module and when I call row[0] it gives me this error IndexError: list index out of range even though it should not be out of the lists range given that I am calling Index 0.

This is a sample of what my data looks like in the csv file. It is only one column.

Caucasian
Black or African American
Caucasian
Asian or Pacific Islander
Caucasian,Hispanic or Latino,Native American or American Indian
Caucasian
Caucasian
Caucasian
Middle Eastern,Asian or Pacific Islander
Asian or Pacific Islander

Heres a sample of my code:

for row in csvReader:
    if row[0] == "Hispanic,Latino,or Spanish origin":
        print("")
    raceList = row[0].split(",")
    elif (len(raceList) > 1):
        csvWriter.writerow(["Mixed Race"])
    elif (row[0] == "African American"):
        csvWriter.writerow(["Black or African American"])
Asked By: Jay Ghosh

||

Answers:

It looks like a row is empty. This produces an empty list when the csvReader tries to read it, and empty lists don’t even have index 0. First thing to do is confirm that this is happening by adding a print statement at the beginning of your for loop:

print(row)

and after running that, you should see [] printed just before you get the IndexError.

However, since it’s a blank line, we probably don’t care about skipping it. To skip the line, just use a continue statement to jump to the next iteration of the for loop:

if len(row) == 0:  # `if not row:` would also work, but this is somewhat more clear
    continue

or handle it differently, depending on what you want to do.

Answered By: Green Cloak Guy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.