so the objective of this exercise is simple but I'm stuck. The program should take a list from user input (eg. tomatoes, fish, milk, watermelons...) and print the longest word in the list. So far I'm only able to print the amount of characters in the longest word.
user_input=input("Type a list of words separated by spaces ")
string_words=user_input
words= string_words.split()
maximum_char = max(len(w)for w in words)
print("The longest word in the list has",maximum_char, "characters")
if len(words) == maximum_char:
print(words)
You can use a key argument for the max() function:
max_word = max(words, key=len)
print('The longest word in the list is "{}" at {} characters.'.format(max_word, len(max_word)))
This key means that max() will determine the "maximum" word based on whatever is returned for that word by the key function, which is len in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With