PythonMastery
Python programs · Strings · beginner

Find the longest word in a sentence in Python

Find the longest word in a sentence with max() and key=len. Punctuation is removed first, and ties between words of the same length are handled.

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

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.

Learn the idea: Working with Strings, Lists & Sequences