Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the word (from user input) with the max amount of characters python

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)
like image 509
Hannah Marie Halverson Avatar asked Dec 04 '25 02:12

Hannah Marie Halverson


1 Answers

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.

like image 101
TigerhawkT3 Avatar answered Dec 05 '25 14:12

TigerhawkT3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!