I am trying to get the length of a list, but that list can contain other lists that are deeply nested (e.g. [[[[[[[]]]]]]]
).
But you have to get any non list elements in the count as well: [1, 2, [3, 4]]
would output 5 (1, 2, 3, 4 and a list). ["a", "b", ["c", "d", ["e"]]]
would output 7.
It first comes to mind to use recursion to solve this problem. I wrote this:
def deep_count(arr, count=0):
if any(type(i) == list for i in arr):
for i in arr:
if type(i) == list:
count += len(arr)
else:
count += 1
return deep_count(arr[1:], count)
return count
It's outputting 9 instead of 7. And if it's just nested lists like [[[]]]
it only outputs 1.