This is what I've tried:
def recursive_list_counter(l):
sum = 0
for e in l:
if type(e) == type([]):
#print e
sum += 1
recursive_list_counter(e)
return sum
# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6])
I want to use recursion to retrieve the number of lists within a list, counting the original list also.
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 outer list is ignored in the count, so the call returns 5, not 6.
Furthermore, you should use isinstance()
to test if an object is of a given type.
If you want to see 6
, count the current list in the function, and leave counting nested lists to the recursive call:
def recursive_list_counter(l):
sum = 1
for e in l:
if isinstance(e, list):
sum += recursive_list_counter(e)
return sum
For your given example, if all you have are numbers within lists, you can try converting to string and counting the number of [
>>> li = [[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6]
>>> str(li).count('[')
6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With