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)
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 helpFile "/home/ranjeet/Desktop/python_plot/marks.py", line 6, in <module>
math_mark_str = fields[5]
IndexError: list index out of range
Python-3.4.3 Parsing-data 12-13 min 50-60 sec
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]
Login to add comment