Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python return number of items in 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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading