'How to return number of items in a list-of-lists?
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 1:[1]
You are reassigning the value of num each time. Change this line to:
num += fun(item)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | oflint_ |
