max() normally compares words by character code, which is close to alphabetical order (capital letters come first). With key=len, it compares their lengths instead and gives back the longest word.
The program
python
import string sentence = input("Enter a sentence: ") words = [word.strip(string.punctuation) for word in sentence.split()] longest = max(words, key=len) print(f"Longest word: {longest} ({len(longest)} letters)")
Typed in this example: Hedy Lamarr invented frequency hopping.. Press Run to type your own.
output
Enter a sentence: Hedy Lamarr invented frequency hopping. Longest word: frequency (9 letters)
How it works
sentence.split()gives the list of words. The last one is "hopping." with its full stop.word.strip(string.punctuation)removes punctuation from the start and the end of each word, so "hopping." becomes "hopping". Without this step, the full stop would be counted as a letter.key=lentellsmax()to calllen()on each word and compare those numbers. On a tie,max()gives the first of the longest words.
Ties
When several words have the same length, find the longest length first, then keep every word with that length:
python
sentence = "Alan wrote about logic and minds" words = sentence.split() longest_length = max(len(word) for word in words) longest_words = [word for word in words if len(word) == longest_length] print(longest_length, longest_words)
output
5 ['wrote', 'about', 'logic', 'minds']
On an empty sentence, max() raises a ValueError, because there is nothing to compare. max(words, key=len, default="") gives back an empty string instead.