Code works sometimes, and sometimes it returns "list index out of range" instead
Question:
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.
Answers:
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)
It could be because the line in the datafile might be empty which is ultimately resulting in an error in the if condition that you have configured.
i.e
error in the following line
datum = line.split()
You can add another if condition before this if condition if datum[1] == searchFirstName:
as if len(datum) > 1:
i.e
if len(datum) > 1:
if datum[1] == searchFirstName:
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.
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)
It could be because the line in the datafile might be empty which is ultimately resulting in an error in the if condition that you have configured.
i.e
error in the following line
datum = line.split()
You can add another if condition before this if condition if datum[1] == searchFirstName:
as if len(datum) > 1:
i.e
if len(datum) > 1:
if datum[1] == searchFirstName: