How to Find the Maximum Length Sub-List in a Nested List in Python
When working with nested lists (lists containing other lists), a common task is finding the sub-list with the most elements. This is useful in data processing, matrix operations, text analysis (finding the longest sentence), and many other scenarios where you need to identify the largest group within a collection.
In this guide, you will learn multiple methods to find the longest sub-list in a nested list, from the most efficient built-in approach to manual loop-based solutions, along with variations for finding just the length or handling edge cases.
Using max() with key=len (Recommended)
The most Pythonic and efficient approach uses the built-in max() function with key=len to compare sub-lists by their length:
nested = [[1, 2], [3, 4, 5], [6]]
longest = max(nested, key=len)
print(longest)
print(f"Length: {len(longest)}")
Output:
[3, 4, 5]
Length: 3
How it works:
max()finds the maximum element in the iterable.key=lentellsmax()to compare elements by their length rather than their values.- The sub-list with the greatest length is returned.
This is the recommended approach - it's concise, efficient (O(n) time), and immediately readable. It works with any iterable of sequences (lists of lists, lists of strings, lists of tuples, etc.).
Getting Only the Maximum Length
If you only need the length (not the sub-list itself):
nested = [[1, 2], [3, 4, 5], [6]]
max_length = max(len(sub) for sub in nested)
print(f"Maximum sub-list length: {max_length}")
Output:
Maximum sub-list length: 3
Using a Loop
An explicit loop gives you full control and is easy to extend with custom logic:
nested = [[1, 2], [3, 4, 5], [6]]
longest = []
max_length = 0
for sub_list in nested:
if len(sub_list) > max_length:
max_length = len(sub_list)
longest = sub_list
print(f"Longest sub-list: {longest}")
print(f"Length: {max_length}")
Output:
Longest sub-list: [3, 4, 5]
Length: 3
This approach is ideal when you need to perform additional operations during the search, such as tracking the index or applying conditions:
nested = [[1, 2], [3, 4, 5, 6], [7, 8, 9], [10]]
longest = []
max_length = 0
longest_index = -1
for i, sub_list in enumerate(nested):
if len(sub_list) > max_length:
max_length = len(sub_list)
longest = sub_list
longest_index = i
print(f"Longest sub-list: {longest}")
print(f"At index: {longest_index}")
print(f"Length: {max_length}")
Output:
Longest sub-list: [3, 4, 5, 6]
At index: 1
Length: 4
Finding All Sub-Lists with Maximum Length
When multiple sub-lists share the maximum length, max() returns only the first one. To get all of them:
nested = [[1, 2, 3], [4, 5], [6, 7, 8], [9]]
max_length = max(len(sub) for sub in nested)
longest_lists = [sub for sub in nested if len(sub) == max_length]
print(f"Maximum length: {max_length}")
print(f"All longest sub-lists: {longest_lists}")
Output:
Maximum length: 3
All longest sub-lists: [[1, 2, 3], [6, 7, 8]]
Using sorted() with reverse=True
Sorting the list by sub-list length in descending order places the longest sub-list first:
nested = [[1, 2], [3, 4, 5], [6]]
sorted_by_length = sorted(nested, key=len, reverse=True)
longest = sorted_by_length[0]
print(f"Longest: {longest}")
Output:
Longest: [3, 4, 5]
While this works, sorting has O(n log n) time complexity - worse than max() which is O(n). Use sorted() only when you also need the sub-lists ordered by length (e.g., to get the top 3 longest):
top_3 = sorted(nested, key=len, reverse=True)[:3]
Handling Edge Cases
Empty Nested List
Calling max() on an empty list raises a ValueError:
nested = []
# This raises: ValueError: max() arg is an empty sequence
longest = max(nested, key=len)
Fix - use the default parameter:
nested = []
longest = max(nested, key=len, default=[])
print(f"Longest: {longest}")
Output:
Longest: []
Nested List Containing Empty Sub-Lists
nested = [[], [1], [], [2, 3], []]
longest = max(nested, key=len)
max_length = max(len(sub) for sub in nested)
print(f"Longest: {longest} (length: {max_length})")
Output:
Longest: [2, 3] (length: 2)
Deeply Nested Lists
If you need to find the longest list at any depth in a deeply nested structure:
def find_longest_recursive(nested):
"""Find the longest list at any depth in a nested structure."""
longest = []
for item in nested:
if isinstance(item, list):
# Check this list itself
if len(item) > len(longest):
longest = item
# Check deeper levels
deeper = find_longest_recursive(item)
if len(deeper) > len(longest):
longest = deeper
return longest
data = [[1, 2], [[3, 4, 5, 6, 7]], [8, [9, 10, 11]]]
result = find_longest_recursive(data)
print(f"Longest list at any depth: {result}")
Output:
Longest list at any depth: [3, 4, 5, 6, 7]
Practical Example: Finding the Longest Word in Grouped Data
sentences = [
["hello", "world"],
["the", "quick", "brown", "fox", "jumps"],
["python", "is", "great"],
]
# Find the sentence with the most words
longest_sentence = max(sentences, key=len)
print(f"Longest sentence ({len(longest_sentence)} words): {' '.join(longest_sentence)}")
# Find the longest word across all sentences
all_words = [word for sentence in sentences for word in sentence]
longest_word = max(all_words, key=len)
print(f"Longest word: '{longest_word}' ({len(longest_word)} characters)")
Output:
Longest sentence (5 words): the quick brown fox jumps
Longest word: 'python' (6 characters)
Comparison of Methods
| Method | Time Complexity | Returns | Handles Ties | Best For |
|---|---|---|---|---|
max(key=len) | O(n) | First longest | ❌ First only | General use (recommended) |
| Loop | O(n) | First longest + index |