Python Practice › List Programs › Program 85
Remove duplicates with a set
Write a Python program to remove duplicates from a list using a set.
Input
[2, 5, 7, 8, 2, 3, 4, 12, 5, 6]
Output
[2, 3, 4, 5, 6, 7, 8, 12] [2, 5, 7, 8, 3, 4, 12, 6]
Approach
set()removes duplicates; usesorted(..., key=items.index)to restore the original order.
Solution
items = [2, 5, 7, 8, 2, 3, 4, 12, 5, 6]unique = set(items)print(sorted(unique))print(sorted(unique, key=items.index))Output
[2, 3, 4, 5, 6, 7, 8, 12] [2, 5, 7, 8, 3, 4, 12, 6]
Line by line
Line 4
Sorting by each value’s first index restores the original order.
Learn the concept
New to this topic? Read the lesson, then come back.