Find the shortest string in list


Find the shortest string in list

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

The syntax to find the shortest string in the list x

min(x, key=len)

The min() 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 shortest string.

Examples

1. Find shortest string in list x

In the following program we take a list of strings in x, and find the shortest string in this list.

Python Program

x = ['apple', 'banana', 'fig', 'mango']
shortest = min(x, key=len)
print(shortest)

Output

fig

2. If there are more than one string with shortest length in the given list

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

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

Python Program

x = ['apple', 'banana', 'mango']
shortest = min(x, key=len)
print(shortest)

Output

apple

Summary

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