How to Find the Shortest Word in a List in Python

How to find the shortest string in a list in Python

The min function has an optional parameter key that lets you specify a function to determine the "sorting value" of each item. We just need to set this to the len function to get the shortest value:

strings = ["some", "example", "words", "that", "i", "am", "fond", "of"]

print min(strings, key=len) # prints "i"

Write function that returns shortest word in a list

Assuming you can't change the word_list itself, you could just use the repr like,

>>> word_list = ["denmark", "sweden", "germany"]
>>> print(word_list[1])
sweden
>>> print(repr(word_list[1]))
'sweden'

or if double quotes is a must then,

>>> print('"{}"'.format(word_list[1]))
"sweden"

Why is my function to find the smallest word in an array not working?

I'll put my code down below and then explain the changes I made:

def word_length(phrase):
splitphrase = phrase.split(" ")

min_word = splitphrase[0] #setting default value as first word
for element in (splitphrase): #for each word in the list
if len(element) < len(min_word): #if the word is shorter than our current min_word
min_word = element #redefine min_word if the current word is shorter
print(min_word)



word_length("hello I am Sam and am tall")

Output:

I

Similar to your code, we start by using the split() function to break our sentence up into words in a list.

To start finding the smallest word, we can define our min_word to initially be splitphrase[0] as our default value.

To determine if other words in the list are min_word, while iterating through every word in the list, if the length of the word we are iterating through in our list is less than the length of current min_word, we redefine min_word to be that current element.

I hope this helped! Let me know if you need any further help or clarification!



Related Topics



Leave a reply



Submit