There are three problems with your code; first, you do nothing with the result of the recursive call. Second, you should use isinstance()
to check if a value is of some type, not type(ob) ==
. Third, instead of using range() and check i to see if the last value was reached, just return False after the loop if nothing was found.
In total:
def nestedListContains(NL, target):
for value in NL:
if isinstance(value, int):
test = value == target
else:
# value is not an int, so it's a list
test = nestedListContains(value, target)
if test:
return True # found target
return False # We finished the loop without finding target
This will throw a TypeError if NL isn't a list at all. Which is perhaps an even better check than isinstance() -- if it can be iterated then it's a list, and if iteration throws a TypeError it's something we should compare to target. I'll also make the naming a bit more standard:
def nested_list_contains(nested_list, target):
try:
for value in nested_list:
if nested_list_contains(value, target):
return True
return False
except TypeError:
# It's a single value
return nested_list == target
But there's an even better way. What we really want to do is flatten the nested list, and check to see if the target is in it. We can turn the above into a generator that flattens iterables recursively:
def flatten_nested_list(nested_list):
try:
for v in nested_list:
for flattened in flatten_nested_list(v):
yield flatten
except TypeError:
yield nested_list
def nested_list_contains(nested_list, target):
return target in flatten_nested_list(nested_list)