Search code examples
pythonpython-2.7indexoutofboundsexception

I want to the sum of the 6th column vlaues


The code:

import csv
cr = csv.reader(open("filename"))
next(cr)
print (sum(float(x[6]) for x in cr))

But getting an error IndexError: list index out of range


Solution

  • The 6th column has an index of 5 rather than 6, so change:

    print (sum(float(x[6]) for x in cr))
    

    to:

    print (sum(float(x[5]) for x in cr))
    

    But if you are still getting IndexError after the change, it may be that some of the rows in your CSV do not have a 6th column, in which case you can add a condition to your generator expression to skip rows that do not have 6 columns:

    print (sum(float(x[5]) for x in cr if len(x) >= 6))