Remove Duplicate Words
Remove duplicate words while preserving first appearances with Python. Students combine a seen set and output list and understand case-sensitive token equality.
1# Take string input2s = input("Enter a string: ")34# Remove duplicate words5words = s.split()6unique_words = []7seen = set()8for word in words:9 if word not in seen:10 unique_words.append(word)11 seen.add(word)1213result = " ".join(unique_words)14print(f"Without duplicates: {result}")
Output
Enter a string: hello world hello programming Without duplicates: hello world programming
In this one
- Deduplicate tokens
- Track seen words
- Preserve first appearance
How it works
- 1
Split the response into words.
- 2
Append unseen tokens and record them in seen.
- 3
Join unique_words with single spaces.
Edge cases
Are Red and red merged?
Are Red and red merged?
No. Matching is case-sensitive.
Does a repeated word disappear entirely?
Does a repeated word disappear entirely?
No. Its first occurrence stays.
What's going on
split creates the tokens. For each word not in seen, the code appends it to unique_words and records it in the set.
Later equal tokens are skipped. Red and red remain distinct because no case normalization occurs. Joining the result inserts single spaces, so original whitespace is not preserved. This is deduplication, not a filter keeping only words that appeared exactly once.
Are Red and red merged? No. Matching is case-sensitive.
Does a repeated word disappear entirely? No. Its first occurrence stays.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why keep unique_words as a list?
Pick an answer to check it.
Question 2
Are Red and red merged?
Pick an answer to check it.
Questions people ask
Are Red and red merged?
No. Matching is case-sensitive.
Does a repeated word disappear entirely?
No. Its first occurrence stays.
Why keep unique_words as a list?
To preserve first-appearance order.
๐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