Find the Smallest String based on Length
To find the smallest of given List of strings based on length in Python, call min() builtin function, pass the strings to compare as arguments to min() function, and also pass len() function for key parameter.
min() function returns the string with the smallest length based on the key.
In this tutorial, we will go through example programs, where we take few string literals and find the smallest among them based on length.
Examples
In the following program, we shall take three strings and find the string with least length using min() function.
Example.py
str1 = 'mango'
str2 = 'watermelon'
str3 = 'apples'
result = min(str1, str2, str3, key=len)
print(f'String with least length is - {result}.')
Output
String with least length is - mango.
You may also provide the strings as a list.
In the following program, we shall take list of strings and find the string with least length using min() function.
Example.py
myList = ['mango', 'watermelon', 'apples']
result = min(myList, key=len)
print(f'String with least length is - {result}.')
Output
String with least length is - mango.
Conclusion
In this Python Tutorial, we have learnt how to find the string with least length, with the help of Python example program.