Given a nested list type structure, I need number of items in the entire list.
For example:
a = [[2, [1, 2]], [[1, 2], [1, 2]]]
# approach 1
def fun(items):
vars = 0
num = 0
for item in items:
print(item, item.__class__)
if item.__class__ == list:
num = fun(item)
else:
vars += 1
return vars + num
# approach 2
str(a).count(",") + 1 # this works but not the approach I am looking for
So in the list a I expect to get 7 items in the overall list, but I see get only 2 from the method that I wrote in approach 1. What went wrong?
>Solution :
You don’t need num; you can just add the result from the recursive call to var:
def fun(items):
vars = 0
for item in items:
if isinstance(item, list):
vars += fun(item)
else:
vars += 1
return vars
a = [[2, [1, 2]], [[1, 2], [1, 2]]]
print(fun(a)) # 7