2

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)) 
10
  • 1
    Is the indentation of else as in the question? Commented May 15, 2020 at 19:27
  • 1
    The k+1 in l[k+1] in the if condition is out of range anyway Commented May 15, 2020 at 19:28
  • Use try, catch, and except for error handling. Commented May 15, 2020 at 19:28
  • 1
    With for k in range(0,len(l)), k will go from 0 to len(l)-1. This causes l[k+1] to get out of range in if l[k+1]>=l[k]+2: when k equals len(l)-1. Commented May 15, 2020 at 19:29
  • Can you specify the exact input you're typing in? Because I can't reproduce your error, nor do I expect to be able to. You'll never iterate off the end of the list because you always return after either of the branches in the if/else. That's probably not really what you want, but you shouldn't be getting an IndexError. Please make sure this is a minimal reproducible example. If it's not reproducible with your code, it doesn't do us much good! Commented May 16, 2020 at 1:47

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

While what you describe is an error in the code, it can't actually happen in the version of the code written in the question because it always returns on the first iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.