Python – Find longest string in list

Find longest string in list

To find the longest string in given list in Python, call max() built-in function, with len() function passed as value for key parameter to max() function.

The syntax to find the longest string in the list x

max(x, key=len)
Run

The max() function compares the strings in the list x based on the return value from key function, which is their length in this case, and returns the longest string.

Examples

1. Find longest string in list x

In the following program we take a list of strings in x, and find the longest string in this list using max() function.

Python Program

x = ['apple', 'banana', 'fig', 'mango']
longest = max(x, key=len)
print(longest)
Run

Output

banana

2. More than one string with longest length

If there are more than one string with the longest length, then the longest string that appears first in the list is returned by max() function.

In the following program there are two strings with the longest length of five: 'apple' and 'mango'. The first element 'apple' is returned by the max() function.

Python Program

x = ['apple', 'fig', 'mango', 'kiwi']
longest = max(x, key=len)
print(longest)
Run

Output

apple

Summary

In this tutorial of Python Examples, we learned how to find longest string in the list using max() builtin function, with the help of examples.