Search code examples
pythonindex-error

Solving error: "list index out of range" in Python


The code is giving the correct answer for all test cases except when I enter a list such as [1,2,3,4,5]. Then it shows:

IndexError: list index out of range.

Why is this happening? Shouldn't the else statement at the end take care of this?

def func(n):
    my_list = n.split()
    l = []

    for i in my_list:
         l.append(int(i))

    if len(l)==0 or len(l)==1:
        return None

    for k in range(0, len(l)):
        if l[k+1] >= l[k] + 2:
            return l[k+1]
        else:
            return None

n = input()

print(func(n)) 

Solution

  • The error appears here:

    for k in range(0,len(l)):
        if l[k+1]>=l[k]+2:
            return l[k+1]
        else:
            return None
    

    Because you iterate up to k = len(l) - 1 inclusively, k + 1 on the last iteration will be len(l), which is out of bounds. Instead, you should change the for to:

    for k in range(0, len(l) - 1):
        ...
    

    Now, the value of k + 1 on the last iteration will be len(l) - 2 + 1 = len(l) - 1, which is within the bounds of l.