Python Practice › List Programs › Program 7

Remove duplicate elements

MediumList Programs · 7 of 100

Write a Python program to remove every duplicate value from a list, keeping the first occurrence of each value in its original position.

Advertisement
Input
[5, 7, 8, 2, 5, 0, 7, 2]
Output
[5, 7, 8, 2, 0]

Approach

  1. Create an empty list for the result.
  2. Visit each value in order and add it only if it is not already in the result.

Solution 1: for loop

Python
list1 = [5, 7, 8, 2, 5, 0, 7, 2]result = [] for value in list1:    if value not in result:        result.append(value) print(result)
Output
[5, 7, 8, 2, 0]

Line by line

Line 1

The input list; 5, 7 and 2 each appear twice.

Line 2

result starts empty and collects each value once.

Line 4

The loop reads the values left to right, so the first occurrence is always seen first.

Line 5

value not in result is True only the first time a value appears.

Line 6

append() adds that first occurrence to the end of result.

Solution 2: dict.fromkeys() (shortest)

Python
list1 = [5, 7, 8, 2, 5, 0, 7, 2]result = list(dict.fromkeys(list1))print(result)
Output
[5, 7, 8, 2, 0]

Line by line

Line 2

Dictionary keys are unique and remember insertion order, so this drops repeats and keeps the first position of each value.

Watch out

list(set(list1)) also removes duplicates, but a set does not keep the original order, so it is not a correct answer when order matters.

The loop is easy to follow but checks in result for every item (O(n²)); dict.fromkeys() runs in O(n) and is what you should use in real code.

Learn the concept

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

More list programs

← All 100 List Programs

Leave a Comment