Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find maximum length sub-list in a nested list in Python
Finding the maximum length sub-list in a nested list is a common task when working with data structures in Python. This article explores different approaches to identify the longest sub-list and return both the sub-list and its length.
Using lambda and max()
The most efficient approach combines lambda with the max() function. The max() function uses a key parameter to determine which sub-list has the maximum length ?
Example
def longest(nested_list):
longest_list = max(nested_list, key=lambda i: len(i))
max_length = max(map(len, nested_list))
return longest_list, max_length
# Driver Code
nested_data = [[1, 2], [2, 45, 6, 7], [11, 65, 2]]
print("Longest List and its length:")
print(longest(nested_data))
Longest List and its length: ([2, 45, 6, 7], 4)
Using len() and max() with Loop
This approach first calculates the maximum length, then iterates through the nested list to find the sub-list that matches this length ?
Example
def longest(nested_list):
longest_list = []
max_length = max(len(x) for x in nested_list)
for sublist in nested_list:
if len(sublist) == max_length:
longest_list = sublist
break # Return first match
return longest_list, max_length
# Driver Code
nested_data = [[1, 2], [2, 45, 6, 7], [11, 6, 2]]
print("Longest List and its length:")
print(longest(nested_data))
Longest List and its length: ([2, 45, 6, 7], 4)
Using map() Function
Similar to the previous approach, but uses map() to apply the len() function to all sub-lists at once ?
Example
def longest(nested_list):
longest_list = []
max_length = max(map(len, nested_list))
for sublist in nested_list:
if len(sublist) == max_length:
longest_list = sublist
break # Return first match
return longest_list, max_length
# Driver Code
nested_data = [[1, 2], [2, 45, 6, 7], [11, 6, 2]]
print("Longest List and its length:")
print(longest(nested_data))
Longest List and its length: ([2, 45, 6, 7], 4)
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Lambda + max() | O(n) | Most concise and efficient |
| Loop with len() | O(n) | When you need more control over selection |
| map() function | O(n) | Functional programming approach |
Conclusion
The lambda with max() approach is the most efficient and readable solution. Use the loop-based methods when you need to handle multiple sub-lists of the same maximum length or require additional processing logic.
