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
Python Replace Single Quotes Except Apostrophes
Python: How to Calculate the Sum of Numbers from a File
Python List - Only Keep Only-Positive or Only-Negative Values
How to Convert a List of Dictionaries to Json in Python/Django
Xlsxwriter: How to Open an Existing Worksheet in My Workbook
Python Calculate Distance Closest Xy Points
Search and Replace a Line in a File in Python
How to Read a File Without Newlines
Changing File Permission in Python
How to Delete a Column That Contains Only Zeros in Pandas
Python3 Tkinter Set Image Size
How to Find the Average of Particular Numbers in a CSV File
Count Frequency of Words in a List and Sort by Frequency
Creating a New Dataframe Column by Comparing Strings of Two Unequal Dataframes
Convert Float to Float Time in Python