saving . . . saved IndexError: list index out of range has been deleted. IndexError: list index out of range has been hidden .
IndexError: list index out of range
Title
Question
I have entered the following code in the editor
math_marks_A = []
for line in open("student_record.txt"):
    fields = line.split(";")
    region_code = fields[0]
    region_code_stripped = region_code.strip()
    math_mark_str = fields[5]
    math_mark = float(math_mark_str)
    if region_code == "A":
        math_marks_A.append(math_mark)

but i am getting the following error after running the file
Traceback (most recent call last):
  File "/home/ranjeet/Desktop/python_plot/marks.py", line 6, in <module>
    math_mark_str = fields[5]
IndexError: list index out of range
please help

Python-3.4.3 Parsing-data 12-13 min 50-60 sec 20-05-24, 10:54 p.m. ranjeet71

Answers:

The error "IndexError: list index out of range"  occurs because the code is trying to access an element in the list fields that doesn't exist. This happens when the line being processed doesn't have enough fields.
You need to add a check to ensure that fields has enough elements before accessing field[5]

22-07-24, 3:24 p.m. ketki.naina


Log-in to answer to this question.