Home > Blockchain >  How to return number of items in a list-of-lists?
How to return number of items in a list-of-lists?

Time:02-03

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?

CodePudding user response:

You don't need num; you can add to var the result from the recursive call:

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

CodePudding user response:

You are reassigning the value of num each time. Change this line to:

num  = fun(item)
  •  Tags:  
  • Related