Find the Longest Word in a Sentence in Python

Splits a sentence into words and returns the longest one using the built-in max() function with len as the key.

Easy Python 3.9+ Aug 9, 2026 Strings & text 15 views 0 copies

Python code

11 lines
Python 3.9+
def find_longest_word(sentence: str) -> str:
    words = sentence.split()
    if not words:
        return ""
    return max(words, key=len)

if __name__ == "__main__":
    test_sentence = "The quick brown fox jumps over the lazy dog"
    longest = find_longest_word(test_sentence)
    print(f"Longest word: '{longest}'")
    print(f"Length: {len(longest)}")

Output

stdout
Longest word: 'quick'
Length: 5

How it works

The sentence.split() method splits the input string on whitespace, producing a list of words. The max() function with key=len compares words by their length and returns the longest one. The function returns an empty string for an empty input to avoid an unhandled ValueError. This approach is concise and uses only built-in functions, making it efficient and readable.

Common mistakes

  • Forgetting to handle empty input, which causes max() to raise ValueError
  • Using split(' ') instead of split() which can produce empty strings from multiple spaces

Variations

  1. Use a loop with a manual comparison if max() is not allowed or for additional logic like handling ties.
  2. Use sorted(words, key=len, reverse=True)[0] if you also need the second-longest word.

Real-world use cases

  • Implementing a word-count feature that highlights the most prominent keyword in user-generated content.
  • Building a text-analysis tool that identifies the longest term in a document for summarization tasks.
  • Writing a game helper that finds the longest possible word from a given set of letters.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.