2

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

blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Possible duplicate of [IndexError: list index out of range and python](https://stackoverflow.com/questions/1098643/indexerror-list-index-out-of-range-and-python) – Nick is tired Sep 27 '18 at 08:40

1 Answers1

1

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))
blhsing
  • 91,368
  • 6
  • 71
  • 106