Search code examples
pythonindexoutofrangeexception

Can you figure out why my code is giving me an IndexOutOfBounds error?


I'm currently trying to populate a SQL database (for an assignment) through Python. I have created a function to help me do that. When I run the function, however, I receive a 'List index out of range" Index error. I would appreciate all and any help!

I have tried reverting to some old code, but it doesn't help with the current problem.

As I understand that there is apparently no "field[1]" (otherwise I wouldn't be receiving this error) I have tried printing each step of my function as it occurs... only to discover that I can, in fact, print the elusive value, but still receive an error about that line?

I have included all the code I believe to be relevant, however, if you think I must be missing something, feel free to contact me. Thank you very much!

def populateStudentTable(textFile,targetTable):
    connection = sqlite3.connect(dbName)
    cursor = connection.cursor()
    numRecs = 0
    dataRecs = []
    textRec = textFile.readline()
    while textRec != "":
        numRecs += 1
        field = textRec.split(", ")
        print(field)
        print(field[0])
        print(field[1])
        textRec = textFile.readline()

When I run the program, it prints the second item in the list: field[1] But then after that, it gives me an error...

['VENNGEOR', 'Georgia', 'Venna', '12', 'Maths', '8596746234']
VENNGEOR
Georgia

This is the error I receive:

Traceback (most recent call last):
File "h:\Digital Solutions\VS Code\Dev.py", line 22, in <module>
numRecs = populateStudentTable(textFile,"tblMentor")
File "h:\Digital Solutions\VS Code\Dev.py", line 14, in 
populateStudentTable:print(field[1])
IndexError: list index out of range

After reading some comments and doing some more debugging of my own, I discovered that "buran" was correct. I had simply left some empty lines and was trying to run a loop on an empty line.


Solution

  • One line in textFile did not contain the number of , characters you expect. When you do field = textRec.split(", ") then resulting field might not have 3 elements as you expect if there was less than two , in the line.

    Examine the content of your file or simply instead of printing elements of field print field itself. This will make it easier for you to understand where you got this wrong.

    Also note you are splitting by ", " (not ","), so be aware of situations like this may also result in your error:

    >>> foo = "a,b,c, d"
    >>> foo.split(", ")
    ['a,b,c', 'd']