Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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"])
like image 449
Jay Ghosh Avatar asked Oct 26 '25 03:10

Jay Ghosh


1 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.

like image 198
Green Cloak Guy Avatar answered Oct 28 '25 19:10

Green Cloak Guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!