Find Shortest Word
Find the shortest token with Python min and key=len. Students guard empty input, compare lengths, and predict first-occurrence behavior when several words tie.
1# Take string input2s = input("Enter a string: ")34# Find shortest word5words = s.split()6if len(words) > 0:7 shortest = min(words, key=len)8 print(f"Shortest word: {shortest}")9else:10 print("No words found")
Output
Enter a string: Hello World Programming Shortest word: Hello
In this one
- Select by minimum length
- Keep first tied results
- Retain punctuation in tokens
How it works
- 1
Split s and check for tokens.
- 2
Call min with key=len.
- 3
Print the selected token or empty-input feedback.
Edge cases
What if two shortest words tie?
What if two shortest words tie?
The first encountered one is selected.
Are punctuation marks stripped?
Are punctuation marks stripped?
No. They remain part of token length.
What's going on
split provides nonempty whitespace-delimited tokens. min(words, key=len) evaluates lengths without replacing the words themselves.
The selected word is printed, not its length. Equal shortest lengths keep the first encountered token. Punctuation counts as part of the token, so a standalone punctuation mark can win. The empty-input branch avoids an invalid min call.
What if two shortest words tie? The first encountered one is selected.
Are punctuation marks stripped? No. They remain part of token length.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does min return here?
Pick an answer to check it.
Question 2
What if two shortest words tie?
Pick an answer to check it.
Questions people ask
What if two shortest words tie?
The first encountered one is selected.
Are punctuation marks stripped?
No. They remain part of token length.
What does min return here?
A selected word.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum