Patternite Logo

Find the longest sublist in a list of lists in Python


A Pythonic approach to find the longest sublist in a list of lists


If you have data that can be represented as a list of lists, one piece of information you may want to know is the length of the longest sublist. For example, text is often stored as a list of lists, where the sublists contain the individual words (or "tokens") of each sentence. Knowing the length of the largest sublist is important for certain data preprocessing steps, such as "padding" all sentences up to a certain length.

The (arguably) most Pythonic approach is shown on line #12, which works by passing the len function as the key argument to the built-in function max. Determining the minimum length just requires swapping max for min. If you instead wanted the longest sublist itself (and not its length), just remove the call to len, as shown on line #16.

You can find the official documentation for the max function here.

Profile picture for JohnGiorgi

| edited

Patternite © 2022

Patternite Logo