adam adam - 19 days ago 9
Python Question

Check whether an element occurs in a list using recursion

def check(x,num,i):
for n in range(len(x)):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
return False
def User(x,num):
return(check(x,num,0))


User([2,6,1,9,7,3],5,0)
this should out put false since 5 is not in the list

checks whether an element occurs in a list recursively

so for example:

Input: a list L read from the keyboard, for example L = [2,6,1,9,7,3]
an element e, for example e = 9

but for some reason, i get an error when the number is not in the list

Answer

The beauty (and purpose) of recursion is that you do not need the loop:

def check(x, num, i):
    if not x[i:]:  # index past length
        return False
    if x[i] == num:
        return True
    return(check(x, num, i+1))

You can also do without the index parameter:

def check(x, num):
    if not x:
        return False
    return x[0] == num or check(x[1:], num)