Remove duplicate elements Medium List 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 Reset Copy Try it ▸
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 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 Reset Copy Try it ▸
list1 = [ 5 , 7 , 8 , 2 , 5 , 0 , 7 , 2 ] result = list ( dict . fromkeys ( list1 )) print ( result )
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 ← Program 6 Separate even and odd numbersProgram 8 → Pairs whose sum is 10← All 100 List Programs