Open In App

Python program to find the longest word in a sentence

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to find the longest word in a sentence.

Using Loop

First split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths.

Python
s = "I am learning Python programming language"

# Split the sentence into words
words = s.split()

# Initialize an empty string to store the longest word
res = ""

# Iterate through each word
for word in words:
  
    # Update 'res' if the current word is longer than 'res'
    if len(word) > len(res):
        res = word

print(res)

Output
programming

Using max() with key Parameter

The idea is similar to the above approach but here after splitting each words from sentence we can use built-in max() function with the key=len parameter for finding the longest word.

Python
s = "I am learning Python programming language"

# Split the sentence into words
words = s.split()

# Find the longest word
res = max(words, key=len)

print(res)

Output
programming

Next Article

Similar Reads