Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively going through a list (python)

Say I have a list x = [1, 2, 3, 4]

Is there a recursive method where i can go through the list to find the value?

I want to ultimately be able to compare a returned value in the list, (or nested list) to an arbitrary number to see it it matches.

I can think a way to do this using a for loop, but i have trouble imagining a recursive method to do the same thing. I know that I can't set a counter to keep track of my position in the list because calling the function recursively would just reset the counter every time.

I was thinking I could set my base case of the function as a comparison between the number and a list of len 1.

I just want some hints really.

like image 288
user3272601 Avatar asked Sep 15 '26 15:09

user3272601


1 Answers

This is not the way to do things in Python, but surely - you can traverse a list of lists recursively:

def findList(lst, ele):
    if not lst:         # base case: the list is empty
        return False
    elif lst[0] == ele: # check if current element is the one we're looking
        return True
    elif not isinstance(lst[0], list): # if current element is not a list
        return findList(lst[1:], ele)
    else:                              # if current element is a list
        return findList(lst[0], ele) or findList(lst[1:], ele)
like image 63
Óscar López Avatar answered Sep 18 '26 04:09

Óscar López