Finding first occurrence

https://app.dataquest.io/m/1018/lists/10/finding-the-first-occurrence

Why isn’t this code working please:

def find_first(list1,obj):
    for i in range(len(list1)):
        if list1[i]==obj:                      
            return i                     
        else:
            return -1
                   
find_first(['a','b','c','a'],'a')

Error:
Function find_first did not return the expected value.

Thank you!

For this exercise, can you tell me how ‘return i’ is making a difference in the code outputs below please.

Code 1

def find_first(list1,obj):
    for i in range(len(list1)):
        if list1[i]==obj:                      
            print(i)                     
        else:
            return -1
                   

        
find_first(['a','b','c','a'],'a')

Output:

0
-1

Code 2
When I add this statement to the if loop:return i

def find_first(list1,obj):
    for i in range(len(list1)):
        if list1[i]==obj:   
	   return i                   
            print(i)                     
        else:
            return -1

Output:

0

(-1 is not included)

Hi @piya,

When a return statement is executed, the function immediately stops.

In your code, instead of looping through all items in the list, the function is returning based on the first value of the list.

if list1[i]==obj:

return i and the function is ended.

If the condition was not met, -1 is returned and the function is ended.

Here is a way you can fix that:

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

In the above code, the loop will run completely and if no match was found, -1 is returned after the loop. Otherwise, i is returned.

Best,
Sahil