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.
Input[5, 7, 8, 2, 5, 0, 7, 2]
Approach
- Create an empty list for the result.
- 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)
Line by line
Line 1The input list; 5, 7 and 2 each appear twice.
Line 2result starts empty and collects each value once.
Line 4The loop reads the values left to right, so the first occurrence is always seen first.
Line 5value not in result is True only the first time a value appears.
Line 6append() 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)
Line by line
Line 2Dictionary keys are unique and remember insertion order, so this drops repeats and keeps the first position of each value.
Watch outlist(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