I’m getting this issue in quite a few different places throughout my code, but I’ll only post the simplest code where I’m getting this issue so I can learn from it.
My code works sometimes, and other times it doesn’t. When it doesn’t work, I get IndexError: list index out of range returned. Its in a class called Students, data is referencing a .txt file that has 800 students in it (give or take).
def SearchStudent(self, data):
students = []
with open(data, "r") as datafile:
for line in datafile:
datum = line.split()
students.append(datum)
searchFirstName = input('Enter students first name: ')
for datum in students:
if datum[1] == searchFirstName:
print(datum)
Error seems to hit the if datum[1] == searchFirstName: part when it happens, but struggling to wrap my head around why it’s happening.
>Solution :
Revise like below to do a basic check:
for datum in students:
if len(datum) > 1 and datum[1] == searchFirstName:
# note index[0] on the list would mean a list length of 1, so looking >1 to get a list containing at least an index[1]
print(datum)