Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the number of nested lists in a list?

The function takes a list and returns an int depending on how many lists are in the list not including the list itself. (For the sake of simplicity we can assume everything is either an integer or a list.)

For example:

x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

count_list(x) # would return 8

I think using recursion would help but I am not sure how to implement it, this is what I have so far.

def count_list(a,count=None, i=None):

    if count==None and i==None:
        count=0
        i=0
    if i>len(a)
        return(count)
    if a[i]==list
       i+=1
       count+=1
       return(count_list(a[i][i],count))
    else:
        i+=1
        return(count_list(a[i]))
like image 490
Oliver Avatar asked Nov 12 '14 00:11

Oliver


People also ask

How do you count nested lists?

A nested list, l , is taken with sub-lists. Count variable is used to count the number of even numbers in the list and is initialized to zero. The nested for loop is used to access the elements in the list. Variable i is used to access sub-lists in the list, and variable j is used to access elements in sub-list i .

How do I find the size of a nested list in Python?

To find the shape (or dimensions) of a nested list or tuple in Python, iterate over each element in the list or tuple and identify its length with the built-in len() function.

How do I count a list of lists?

Use list. __len__() to count elements in a list. We can directly call the __len__() member function of list to get the size of list i.e.


3 Answers

You can use a recursion function as following:

In [14]: def count(l):
    ...:     return sum(1 + count(i) for i in l if isinstance(i,list))
    ...: 

In [15]: 

In [15]: x=[1,2,[[[]]],[[]],3,4,[1,2,3,4,[[]] ] ]

In [16]: count(x)
Out[16]: 8
like image 126
Mazdak Avatar answered Sep 19 '22 15:09

Mazdak


This seems to do the job:

def count_list(l):
    count = 0
    for e in l:
        if isinstance(e, list):
            count = count + 1 + count_list(e)
    return count
like image 37
lvella Avatar answered Sep 19 '22 15:09

lvella


Here is a non-recursive solution:

  1. First, put every items of the list into a stack
  2. Keep popping an item off the stack until it is exhausted
  3. If the item is a list: a) count it, b) push every items in in to the stack

The code:

def count_list(lst):
    """ Given a master list, count the number of sub-lists """
    stack = lst[:]
    count = 0
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            # If the item is a list, count it, and push back into the
            # stack so we can process it later
            count += 1
            stack.extend(item)
    return count
like image 41
Hai Vu Avatar answered Sep 18 '22 15:09

Hai Vu