Search code examples
pythonloopsdictionaryindex-error

Why am I getting this "list index out of range" error?


def numline(name) returns a number of lines in of a text file

def anyLine(name,n) returns any line of a text file and each line (on my text file) have three tabs ('\t')

If I run the program without the loop, I get my desired answer, but when I use for loop I keep getting the error

(dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
IndexError: list index out of range)

This is my code:

def main(name):

    for i in range(0, numLine(name)):
        a_string = anyLine(name, i).split('\t')
        dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]

    for key in dictConcepts:
         print(key, ':', dictConcepts[key])

Solution

  • Right now, if:

    a_string = anyLine(name, i).split('\t')
    

    does not produce at least a length three list, (i.e. \t is present twice in the line) your code will fail with an index error.

    You can program a try/except so you're not indexing things that do not exist:

    a_string = anyLine(name, i).split('\t')
    try:
        dictConcepts[a_string[0], a_string[2].rstrip('\n')] = a_string[1]
    except IndexError:
        print('something is not right here')