Finding length of the longest list in an irregular list of lists

Python 3.3 version:

def lengths(x):
    if isinstance(x,list):
        yield len(x)
        for y in x:
            yield from lengths(y)

usage:

>>> l = [[], [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]], [1,2,3,4,5]]
>>> max(lengths(l))
7

In python 2.6+ you don't have the yield from statement (was introduced in python 3.3), so you have to change the code slightly:

def lengths(x):
    if isinstance(x,list):
        yield len(x)
        for y in x:
            for z in lengths(y):
                yield z

These simple few lines works for me, my list is a nested one (list of lists)

#define the function#
def find_max_list(list):
    list_len = [len(i) for i in list]
    print(max(list_len))

#print output#
find_max_list(your_list)

Here is a recursive solution for any depth list:

def longest(l):
    if not isinstance(l, list):
        return 0
    return max(
            [len(l)] 
            + [len(subl) for subl in l if isinstance(subl, list)] 
            + [longest(subl) for subl in l]
            )

Indeed, recursion can solve this.

def longest(lst):
    if type(lst) is not list:
        return 0
    max = len(lst)
    for i in lst:
        max_i = longest(i)
        if max_i > max:
            max = max_i
    return max

Tags:

Python

List