Find Longest Word in Python

Find the longest word in a sentence.

BeginnerString ProgramsExample 14 of 25
find-longest-word.py
Run in browser
1# Program to find the longest word in a sentence
2
3sentence = input("Enter a sentence: ")
4
5words = sentence.split()
6
7if not words:
8 print("No words found.")
9else:
10 longest = max(words, key=len)
11 print("Longest word:", longest)

Output

Enter a sentence: Python string programs collection
Longest word: collection

What's going on

We split the sentence into words and use max with key=len to find the longest one.