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?
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.
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.
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.
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.
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] )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With