Recursively find first occurrence of a number in a list using Python

Recursion is a process where a function calls itself but with a base condition. A base condition is required in order to stop a function to call itself again.
In this tutorial, we will learn how to find the first occurrence of a number in a list recursively in Python. So, let’s get started.

Find the first occurrence of a number in a list recursively

First, we define a function check() that will take a list(n), index(i) and required number(j) as an argument.

def check(n,i,j):

Now, we will use if-else statements.

if(i==len(n)):
    return "Not Found"
elif(j==n[i]):
    return i

If index i is equal to the length of the list(len(n)), that means we have traversed the list and j is not found. Therefore we return a string “Not Found”.
Else if j==n[i] i.e, if number to be found and element at ith index are equal. it means our number is found and returns the index i.
And if both the conditions are false, we return our function check()  with list n, j, and next index i+1 so that it traverses the list from the next index.

else:
    return check(n,i+1,j)

This is how our code looks like.

def check(n,i,j):
    if(i==len(n)):
        return "Not Found"
    elif(j==n[i]):
        return i  
    else:
        return check(n,i+1,j)

Finally, it’s time to call our function.

print("Your number found at index",check([1,2,3,2,5,6,6],0,2))
print("Your number found at index",check([1,2,3,2,5,6,6],0,4))
print("Your number found at index",check([1,2,3,2,5,6,6],0,6))

The output of our program will be like you can see below:

Your number found at index 1
Your number found at index Not Found
Your number found at index 5

Also, learn:

 

Leave a Reply

Your email address will not be published. Required fields are marked *