I am trying to make a recursive function that goes through any level of nested list with single character strings and returns True or False whether a given character is in that list.
This is my code:
def inlist(character, lists):
"""Checks if a given character is in a list of any level"""
if lists[0] == character:
return True
elif isinstance(lists[0], list):
return inlist(character,lists[0])
elif not lists[0] == character:
return inlist(character,lists[1:])
else:
return False
When i run the code with: ("c", [["a", "b","c", "d"],"e"])
it seems to be working fine. However, when i am typing the list in this way: ("c", [["a", "b",],["c", "d"],"e"])
It gives me an error, which says: IndexError: list index out of range
Can i not write a nested list in this way? If so, why? Or is there anything wrong with my code that makes it not go through the whole list?
lists[0]before checking iflistshas any elements.ifinto anelif, then have theifsomething likeif not list:. No need to nest.elifwill fire and return False even though one of the later lists might have returned True.