Contents
Find 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)
Run 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)
Run Output
fig
2. More than one string with shortest length
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)
Run 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.
Related Tutorials
- How to Append List to Another List in Python? – list.extend(list)
- Python List of Functions
- Python – Traverse List except Last Element
- Python – List of Strings
- Python – Convert List to Dictionary
- Python List – Add Item
- How to Access List Items in Python?
- Python Program to Find Duplicate Items of a List
- How to Get List of all Files in Directory and Sub-directories?
- Python – Check if List Contains all Elements of Another List