-1

My problem is that the average value on this won't show up as it returns as an error

Traceback (most recent call last):
(file location), line 29, in <module>
    average_score = [[x[8],x[0]] for x in a_list]
(file location), line 29, in <listcomp>
    average_score = [[x[8],x[0]] for x in a_list]
 IndexError: list index out of range

the code

   import csv
class_a = open('class_a.txt')
csv_a = csv.reader(class_a)
a_list = []
for row in csv_a:
    row[3] = int(row[3])
    row[4] = int(row[4])
    row[5] = int(row[5])
    minimum = min(row[3:5])
    row.append(minimum)
    maximum = max(row[3:5])
    row.append(maximum)
    average = sum(row[3:5])//3
    row.append(average)
    a_list.append(row[0:8])
print(row[8])

this clearly works when I test out the values 0 to 7 ,even if I change the location of the avarage sum I still get the error

Kevin
  • 74,910
  • 12
  • 133
  • 166
NeptorSV
  • 5
  • 1
  • 3
  • 1
    I don't think that's the code that's causing the error, because it's not at least 29 lines long, and `average_score = [[x[8],x[0]] for x in a_list]` doesn't appear in it. – Kevin May 11 '15 at 14:29

1 Answers1

2

When you call a_list.append(row[0:8]) you're appending an array using only indexes 0, 1, 2, 3, 4, 5, 6, and 7 from row. This means that when you later iterate a_list, the x variable only has indexes up to 7, and you're trying to access 8.

Quick example:

>>> row = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = row[:8]
>>> x[8]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> x[7]
7
>>>
Blixt
  • 49,547
  • 13
  • 120
  • 153
  • Thank you, but I have one final problem where the same thing is returned `Traceback (most recent call last): (file location), line 29, in average_score = [[x[8],x[0]] for x in a_list] (file location), line 29, in average_score = [[x[8],x[0]] for x in a_list] IndexError: list index out of range` and the problemroots back to this line 29 which is `average_score = [[x[8],x[0]] for x in a_list] print("\nCLASS A\nThe average score from highest to lowest \n") for ave_scr in sorted(average_score): print(ave_scr)` – NeptorSV May 15 '15 at 13:45
  • @NeptorSV: I believe that's the same error. You're creating lists with indexes 0...7 but you're trying to access index 8 which doesn't exist (out of range). Try adjusting the 8 to 7 and it'll probably work. And keep in mind that when you use slices like `[0:8]` the first number is *inclusive* (it will be in the result) and the second is *exclusive* (the number before it will be in the result, but not the number itself). This means that 0:8 becomes the numbers 0, 1, 2, 3, 4, 5, 6, and 7. – Blixt May 15 '15 at 15:15