Your recursive call ignores what is returned. Add the return value:
def recursive_list_counter(l):
sum = 0
for e in l:
if isinstance(e, list):
sum += 1
sum += recursive_list_counter(e)
return sum
Note that the external list is ignored in the counter, so the call returns 5, not 6.
In addition, you should use isinstance()to check whether an object is of a given type.
If you want to see 6, count the current list in a function and leave the count of nested lists to recursive calls:
def recursive_list_counter(l):
sum = 1
for e in l:
if isinstance(e, list):
sum += recursive_list_counter(e)
return sum
source
share