Check whether an element is there or not in a list using recursion in python

Question:

Here is the code which I wrote for checking whether an elements is there or not in a list using recursion in Python. According to the flow of the program, it should return True, but instead returns None. Please help in explaining where I went wrong. Thanks in advance.

def numCheck(list,num):
    if len(list) == 0:
        return
    if list[0] == num:
        return True
    else:
        numCheck(list[1:],num)
print(numCheck([1,2,3],2))
Asked By: Vedant

||

Answers:

You need to return the result of the function call:

def numCheck(list,num):
  if len(list) == 0:
    return False
  if list[0] == num:
    return True
  return numCheck(list[1:],num)

print(numCheck([1,2,3],2))

Output:

True
Answered By: Ajax1234
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.