Search code examples
python-2.7indexoutofrangeexceptionindex-error

list index is out of range in try/raise/exception


I have the following code:

for i in range(len(str(hoursList))):
    try:
        g(hoursList[i])
    except Exception as ex:
        print(str(nameList[i]) + " " + "has more than 80 hours worked!")

When I run the code, I get an error saying "IndexError: list index out of range". I'm wondering if its because I have hoursList[i], but when I take out the [i], the loop runs too many times. My nameList and hoursList has the following in it, respectively.

['Michael Johnson', 'Sue Jones', 'Tom Spencer', 'Mary Harris', 'Alice Tolbert', 'Joe Sweeney', 'Linda Smith', 'Ted Farmer', 'Ruth Thompson', 'Bob Bensen'] [8.75, 8.75, 8.75, 8.75, 8.75, 8.75, 11.0, 11.0, 5.25, 5.0]


Solution

  • What is happening when you are doing len(str(hoursList)) is you are turning the entire list into a string then going through and returning an i for each number, space, and , of the new string. For example:

    len(str(["hello", "world"])) == 18

    But if you do this:

    len(["hello", "world"]) == 2

    So when you are in the for i loop you end up going over how many entries are actually in the hoursList.

    Change your loop to be:

    for i in range(len(hoursList)):
        try:
            g(hoursList[i])
        except Exception as ex:
            print(str(nameList[i]) + " " + "has more than 80 hours worked!")