Remove Duplicate Words

Remove duplicate words from string.

IntermediatePhase 5 - Category 3: Word OperationsExample 9 of 10
remove-duplicate-words.py
1# Take string input
2s = input("Enter a string: ")
3
4# Remove duplicate words
5words = 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)
12
13result = " ".join(unique_words)
14print(f"Without duplicates: {result}")

Output

Enter a string: hello world hello programming
Without duplicates: hello world programming

What's going on

Keep only first occurrence of each word.

Key Concepts:

Use set to track seen words
Add to result if not seen
Preserves order