Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have to find the longest list inside a list of lists.

For example:

longest([1,2,3]) returns 3

longest([[[1,2,3]]]) also returns 3 (inner list is 3)

longest([[], [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]], [1,2,3,4,5]]) returns 7 (list [3,[4,5],[2,3,4,5,3,3], [7], 5, [1,2,3], [3,4]] contains 7 elements)

Right now I have this code, but it doesn't do the trick with the first two examples.

def longest(list1):     longest_list = max(len(elem) for elem in list1)     return longest_list 

Maybe recursion will help?

like image 314
Liis Krevald Avatar asked Jun 17 '15 21:06

Liis Krevald


People also ask

How do you find the maximum length of two lists in Python?

Similarly, we use the for loop to find length of each list and output the maximum length. In this method we use Python map function to iterate over the inner lists to create a list of lengths, then get the maximum with max function. One more method in Python to find the longest length list is the lambda operator.

How do you find the largest list in a list Python?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

Can you use LEN () on a list?

A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function.

How do I find the length of a sublist?

Using len and max In this approach, we first find the sub-list with maximum length and then loop through the elements of the list to find out which sublist match that length. We use the max and len function to do this calculation.


2 Answers

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) 
like image 74
FeiLiao Avatar answered Sep 27 '22 19:09

FeiLiao


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]             ) 
like image 45
cr1msonB1ade Avatar answered Sep 27 '22 20:09

cr1msonB1ade