Find the Shortest Word(String) in a Python List

3 ways to find the shortest word(string) in Python list:

  1. Using min() function
  2. Using for loop
  3. Using reduce()

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

Visual Representation of Find the Shortest Word(String) in a Python List using min function

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

Visual Representation of Using reduce()

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.