3

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 need to loop through `words` to find a word whose length is `maximum_char`. In your comparison, len(words) is *not* what you want: it's the number of words entered. Another problem: if the words entered are to be separated by commas, then you need to use `.split(',') and then use `len(w.strip())` to get rid of whitespace when evaluating `max`. Either that, or just enter the words separated by spaces. – BrianO Oct 01 '15 at 22:24
  • Does this answer your question? [Searching a list for the longest string](https://stackoverflow.com/questions/26618815/searching-a-list-for-the-longest-string) – Tomerikoo Jul 28 '21 at 17:42

1 Answers1

4

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.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97