Search code examples
pythonpython-3.xindex-error

Python - IndexError: list index out of range NOT being thrown when it should be


Not sure if this is BECAUSE of Jupyter Notebook or just that Python HANDLES the exception, but I was solving a problem involving algorithms with a friend

While whiteboarding the code, I used Python!

exampleList = ['a', 'b', 'c', 'd', 'e']

for i in range(0, len(exampleList)):
    for j in range(i + 1, len(exampleList)):
        print(exampleList[i], exampleList[j])

Basically, the debate was that.. This code (a similar one, I have used a simple example to illustrate) involving two for loops MUST throw an error! Because, index i reached len(exampleList) - 1, and index j technically will become len(exampleList) and at that point, print(exampleList[i], exampleList[j]) cannot work! It looks like while running the code, it does print out perfectly, and I think HANDLES the IndexError: list index out of range exception!

My question is.. Is this supposed to be intended behaviour in Python? Because the person I was debating with ended up telling me that 'The people conducting your interview notice these things! You must be able to explain every line.'

I would like to understand how this part is handled so I can explain why this does not throw an error!


Solution

  • The range function is inclusive of lower bound, but exclusive of upper bound.

    Your example list has 5 elements. This means that the first loop is running range(0,5), making the max i=4. Which makes the second loop have a max value of range(5,5), which is an empty list. Iterating over an empty list causes 0 iterations.

    >>> exampleList = ['a', 'b', 'c', 'd', 'e']
    >>> len(exampleList)
    5
    >>> range(0, 5)
    [0, 1, 2, 3, 4]
    >>> range(5,5)
    []