Python Practice › List Programs › Program 85

Remove duplicates with a set

EasyList Programs · 85 of 100

Write a Python program to remove duplicates from a list using a set.

Advertisement
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

  1. set() removes duplicates; use sorted(..., key=items.index) to restore the original order.

Solution

Python
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.

More list programs

← All 100 List Programs

Leave a Comment