Search code examples
pythonlistfor-loopindexoutofrangeexception

Why do I get index out of range error? The error is as follows,


Here is the error:

enter image description here

My code:

def isVariable(line):
    modifier = ['private','protected','public']
    datatype = ['String','int','float','boolean']
    status = False
    linelist = list(line.split())

    if(linelist[0] in modifier):
        if(linelist[1] in datatype):
            if(';' in linelist[len(linelist)-1]):
                status = True
                return status
    else:
        return status

f = open('Student.java','r')
vList = []

for line in f:
    status = isVariable(line)
    if status == True:
        vList.append(line)
  

print(vList)

What is wrong?


Solution

  • You get the error because in that line of code,

    linelist is empty, and so, you cannot get the first (index 0) element of the list.

    The reason a it can be empty is empty lines in the file.