Suppose you have a list of large strings and you want to find the shortest word in the list. Then how you can do that? In this entire tutorial, you will know the various methods to find the shortest word in the list in Python.
Sample List to Find the shorted word
Let’s create a sample list of string elements and find the smallest string length words in the next section.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
Find the shortest word in a list using the min() method
The first method to find the shortest word is using the min() method. Python provides you with this inbuilt method. You will take two arguments one is the input list and the other is an argument.
Below is the syntax of the min() method.
min( your_input_list, list_length)
Let’s find the shorted word.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
shortest_word = min(sample_list,key=len)
print(shortest_word)
Output
UK

Finding the shorted words using the loop
You can also use the loops to find the shortest words in the loop. In this, you have to compare each length of strings with the minimum length while iteration. And you will assign the shorted word to dummy variable.
Execute the below lines of code.
sample_list = ["India","America","Australia","Russia","South Africa","UK"]
min_len = 100
shortest_element = ""
for element in sample_list:
if(len(element) < min_len):
min_len = len(element)
shortest_element = element
print(shortest_element)
Output
UK

These are the method to find the shortest word in the list in python. You can use both of them according to your convenience. But I will suggest you to use the first method as it is fast compared to the second method.
Leave a Reply