Python Program to Find Longest Word in String
split() and then using max(words, key=len) to get the longest word.Examples
How to Think About It
Algorithm
Code
text = input("Enter a string: ") words = text.split() longest_word = max(words, key=len) print("Longest word:", longest_word)
Dry Run
Let's trace the input 'I love programming' through the code
Input string
text = 'I love programming'
Split string into words
words = ['I', 'love', 'programming']
Find longest word
longest_word = 'programming' because it has length 11 which is longest
Print result
Output: Longest word: programming
| Word | Length |
|---|---|
| I | 1 |
| love | 4 |
| programming | 11 |
Why This Works
Step 1: Splitting the string
Using split() breaks the string into words separated by spaces, making it easier to check each word.
Step 2: Finding the longest word
The max() function with key=len compares words by their length and returns the longest one.
Step 3: Outputting the result
Printing the longest word shows the user which word in the string is the longest.
Alternative Approaches
text = input("Enter a string: ") words = text.split() longest_word = '' for word in words: if len(word) > len(longest_word): longest_word = word print("Longest word:", longest_word)
text = input("Enter a string: ") words = text.split() longest_word = sorted(words, key=len)[-1] print("Longest word:", longest_word)
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and checking each word length takes linear time proportional to the number of words, so O(n).
Space Complexity
Splitting creates a list of words, so space used is proportional to the number of words, O(n).
Which Approach is Fastest?
Using max() with key=len is fastest and most readable compared to sorting or manual loops.
| Approach | Time | Space | Best For |
|---|---|---|---|
| max() with key=len | O(n) | O(n) | Simple and efficient |
| Manual loop | O(n) | O(n) | Clear logic for beginners |
| sorted() by length | O(n log n) | O(n) | When sorted order is also needed |
max(words, key=len) for a simple and efficient way to find the longest word.