Going fast! #DataquestChallenge Premium Annual Offer:
500 get 50% & the next 1000 get 40% off.

Problem 10: List

Screen Link:

My Code:

def find_first(listt, obj):
    for a in range(len(listt)):
        if listt[a]==obj:
            return a
        if a==len(listt)-1:
            return -1

What I expected to happen:
Get the index/-1

What actually happened:

Function find_first did not return a value with the expected type. We expected int but got NoneType instead.

When provided with an error, try to work backwards and see what edge case you might be missing here.

Your error states -

So, calling your function is returning None (NoneType). Functions in Python return a None when they are called but no return statement ends up running. So, in that case, the function returns a None.

Given your current code, when would the function return a None? When both of your return statements don’t run at all. So, that means

The above code will run but the if conditions are not met at all. Now, think of the input. For what input would the above if conditions be False? That is -

  • obj is not inside listt.
  • No value of a would equal to len(listt)-1

The only input that satisfies both of the above is an empty list. If you run your code with the following -

print(find_first([], 3))

You will get an output None. The platform’s Grader is checking for an empty input as well, and your current implementation is not matching the expected output. So, focus on modifying your code for that input.