Remove duplicate elements
Write a Python program to remove every duplicate value from a list, keeping the first occurrence of each value in its original position.
[5, 7, 8, 2, 5, 0, 7, 2]
[5, 7, 8, 2, 0]
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
list1 = [5, 7, 8, 2, 5, 0, 7, 2]result = [] for value in list1: if value not in result: result.append(value) print(result)[5, 7, 8, 2, 0]
Line by line
The input list; 5, 7 and 2 each appear twice.
result starts empty and collects each value once.
The loop reads the values left to right, so the first occurrence is always seen first.
value not in result is True only the first time a value appears.
append() adds that first occurrence to the end of result.
Solution 2: dict.fromkeys() (shortest)
list1 = [5, 7, 8, 2, 5, 0, 7, 2]result = list(dict.fromkeys(list1))print(result)[5, 7, 8, 2, 0]
Line by line
Dictionary keys are unique and remember insertion order, so this drops repeats and keeps the first position of each value.
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.