Find maximum length sub-list in a nested list in Python

PythonServer Side ProgrammingProgramming

we often deal with nested lists when doing data analysis in python. In this article, we will see how to find out the longest list among the elements in a nested list and then print this along with its length.

Using lambda and map

We declare a nested list and give it as input to the lambda function along with its length. Finally, we apply the max function to get the list with maximum length as well as the length of such list.

Example

 Live Demo

def longest(lst):
   longestList = max(lst, key = lambda i: len(i))
   maxLength = max(map(len, listA))
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,65,2]]
print("Longest List and its length:\n",longest(listA))

Output

Running the above code gives us the following result −

Longest List and its length:
([2, 45, 6, 7], 4)

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.

Example

 Live Demo

def longest(lst):
   longestList = []
   maxLength = max(len(x) for x in listA)
   for i in listA:
      if len(i) == maxLength :
         longestList = i
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,6,2]]
print("Longest List and its length:\n",longest(listA))

Output

Running the above code gives us the following result −

Longest List and its length:
([2, 45, 6, 7], 4)

Using map

This is a similar approach as the above program but we are using the map function to find out the sublist with maximum length.

Example

 Live Demo

def longest(lst):
   longestList = []
   maxLength = max(map(len,listA))
   for i in listA:
      if len(i) == maxLength :
         longestList = i
   return longestList, maxLength
# Driver Code
listA = [[1,2], [2,45,6,7], [11,6,2]]
print("Longest List and its length:\n",longest(listA))

Output

Running the above code gives us the following result −

Longest List and its length:
([2, 45, 6, 7], 4)
raja
Published on 25-Jan-2021 07:16:22
Advertisements