Open In App

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

Last Updated : 27 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Python, we often work with nested lists (lists inside lists), and sometimes we need to find out which sub-list has the most items. In this article, we will explore Various methods to Find the maximum length of a sub-list in a nested list.

Using max() Function with key=len

The simplest and most efficient way to find the longest sub-list is to use the built-in max() function. The max() function helps us find the largest item in a list. By using the key=len argument, we tell Python to compare the lengths of the sub-lists instead of the sub-lists themselves.

Python
a = [[1, 2], [3, 4, 5], [6]]

# Find the longest sub-list
b = max(a, key=len)

print(b)

Output
[3, 4, 5]

Other methods of finding the maximum length sub-list in a nested list are:

Using a Loop

Iterate through the nested list and keep track of the sub-list with the maximum length. This method gives us the flexibility to add more logic or custom conditions if needed.

Python
a = [[1, 2], [3, 4, 5], [6]]

# Initialize variables to track the longest sub-list
b = []
max_length = 0

# Loop through each sub-list in the nested list
for sub_list in a:
    if len(sub_list) > max_length:
        b = sub_list
        max_length = len(sub_list)

print(b)

Output
[3, 4, 5]

Using List Comprehension with zip()

List comprehension is a Python feature that lets us write compact and readable code. Generate a tuple of lengths and corresponding sub-lists, then extract the sub-list with the maximum length.

Python
a = [[1, 2], [3, 4, 5], [6]]

# Use list comprehension to find sub-lists with the maximum length
b = max((sublist for sublist in a), key=len)

print(b)

Output
[3, 4, 5]

Using sorted() with reverse=True

Another method to find the longest sub-list is by sorting the nested list by the length of the sub-lists in descending order. After sorting, the first element will be the longest sub-list.

Python
a = [[1, 2], [3, 4, 5], [6]]

# Sort the list by length of sub-lists in descending order
sorted_lists = sorted(a, key=len, reverse=True)

# first element is the longest sub-list
b = sorted_lists[0]

print(b)

Output
[3, 4, 5]

Next Article

Similar Reads