3 ways to find the shortest word(string) in Python list:
Method 1: Using min() function
The min() function can find the item with the smallest value in a list.
By using len as the key, it compares the lengths of the words.
Visual Representation
Example
languages = ["Python", "Java", "JavaScript", "PHP", "C++"]
shortest_word = min(languages, key=len)
print("The shortest word in the list is:", shortest_word)
Output
The shortest word in the list is: PHP
In the above example, both ‘PHP’ and ‘C++’ have the same length of 3 characters, but it returns the first item it finds with the smallest length.
Method 2: Using for loop
The for loop iterates through each word in the languages list and keeps track of the shortest word as it iterates.
Example
languages = ["Python", "Java", "JavaScript", "PHP", "C++"]
shortest_word = languages[0]
for word in languages:
if len(word) < len(shortest_word):
shortest_word = word
print("The shortest word in the list is:", shortest_word)
Output
The shortest word in the list is: PHP
Method 3: Using reduce()
You can use the reduce() function with a lambda function to iteratively compare the lengths of each word and return the shortest one.
Visual Representation
Example
from functools import reduce
def find_shortest_word_reduce(words):
return reduce(lambda a, b: a if len(a) < len(b) else b, words)
languages = ["Python", "Java", "JavaScript", "PHP", "C++"]
shortest_word = find_shortest_word_reduce(languages)
print("The shortest word in the list is:", shortest_word)
Output
The shortest word in the list is: C++
In the above example, the output is ‘C++’ and not ‘PHP’ as in previous examples.
This is because when multiple words of the same shortest length are present, the last one in the list is retained at the end of the reduction process.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.