IndexError: list index out of range

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Edward Hobbs
    New Member
    • Dec 2011
    • 2

    IndexError: list index out of range

    This is my first post, so please be patient with me.. So i've been coding in python for about a month, and i'm not exactly brilliant, so i'm stumped. The system is a basic login (A-Level work) for a "merit system", however the list cannot get past the first user in the class?

    Code:
    Code:
    def findStudent(username):
        for i in range(len(students)):
            if students[i][0] == username:
                return i
        return -1
    Sorry if i've been vague, feel free to ask any further questions

    thanks in advance,
    Ed
    Last edited by bvdet; Dec 16 '11, 09:24 PM. Reason: Add code tags
  • Edward Hobbs
    New Member
    • Dec 2011
    • 2

    #2
    Okay copy/paste messed up the indents, try #2:

    def findStudent(use rname):
    ____for i in range(1,len(stu dents)):
    ________if students[i][0] == username:
    ________return i
    ____return -1
    Last edited by Edward Hobbs; Dec 16 '11, 09:14 PM. Reason: formatting still

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Ed,

      Indents display properly when you use code tags.

      What is students? From your code I would expect it to be a list of lists. If you use range(1, len(students)), you will always skip the first element (the first element of a list is always at index 0). If students is empty, you will get an IndexError.

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        Can you post the error and perhaps a simple example of the code failing.

        Comment

        • Glenton
          Recognized Expert Contributor
          • Nov 2008
          • 391

          #5
          Good point BVDET.
          If you add in a line like this:
          Code:
          if len(student[i])==0: continue
          after the for statement and before the if statement you'll be able to skip empty records. Of course it would be better not to have empty records but it depends how things are set up.

          Another thing that is quite common is to set up a class object for student instead of a list. A list is unwieldy because you need to keep track of what each entry corresponds to and is therefore prone to error. A student object could have all the variables, and could also be printed using special methods.

          Comment

          Working...