Python Practice › String Programs › Program 20

Remove duplicate words

EasyString Programs · 20 of 106

Write a Python program to remove duplicate words (ignoring case) and keep the first occurrence.

Advertisement
Input
"John jany sabi row john sabi"
Output
John jany sabi row

Approach

  1. Track lower-cased words already seen.

Solution

Python
text = "John jany sabi row john sabi"seen = set()result = []for w in text.split():    if w.lower() not in seen:        seen.add(w.lower())        result.append(w)print(" ".join(result))
Output
John jany sabi row

Line by line

Line 5

Comparing lower-cased words treats “John” and “john” as the same.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs