Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Code works sometimes, and sometimes it returns "list index out of range" instead

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading