Python Practice › String Programs › Program 68
First repeated word
Write a Python program to find the first word that repeats.
Input
"ab bc ca ab bd"
Output
ab
Approach
- Remember words seen; return the first one seen again.
Solution
def first_repeated(text): seen = set() for w in text.split(): if w in seen: return w seen.add(w) return None print(first_repeated("ab bc ca ab bd"))Output
ab
Learn the concept
New to this topic? Read the lesson, then come back.