Problem 10: Duplicate Removal
Source: Dev.to
Problem Description
We need a function that removes duplicates from a list while preserving the original order of elements.
Example
remove_duplicates([1, 2, 2, 3, 1, 4]) should return [1, 2, 3, 4].
Solution
def remove_duplicates(lst):
"""
Removes duplicates from a list while maintaining order.
"""
seen = set()
result = []
for i in lst:
if i not in seen:
seen.add(i)
result.append(i)
return result
# Test case
print(remove_duplicates([1, 2, 2, 3, 1, 4]))
# Output: [1, 2, 3, 4]
Explanation
-
Initialize
seen = set()– stores elements that have already been encountered.result = []– will contain the final list without duplicates.
-
Iterate through the input list
for i in lst:- If
iis not inseen, it is the first occurrence:- Add it to
seen:seen.add(i). - Append it to
result:result.append(i).
- Add it to
- If
iis already inseen, skip it.
- If
-
Return the
resultlist, which now holds each unique element in the order of its first appearance.
Walk‑through with the example [1, 2, 2, 3, 1, 4]
| Step | Element i | Action | seen | result |
|---|---|---|---|---|
| 1 | 1 | Not in seen → add & append | {1} | [1] |
| 2 | 2 | Not in seen → add & append | {1, 2} | [1, 2] |
| 3 | 2 | Already in seen → skip | {1, 2} | [1, 2] |
| 4 | 3 | Not in seen → add & append | {1, 2, 3} | [1, 2, 3] |
| 5 | 1 | Already in seen → skip | {1, 2, 3} | [1, 2, 3] |
| 6 | 4 | Not in seen → add & append | {1, 2, 3, 4} | [1, 2, 3, 4] |
Final result: [1, 2, 3, 4].