Problem 10: Duplicate Removal

Published: (January 20, 2026 at 01:56 AM EST)
2 min read
Source: Dev.to

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

  1. Initialize

    • seen = set() – stores elements that have already been encountered.
    • result = [] – will contain the final list without duplicates.
  2. Iterate through the input list

    for i in lst:
    • If i is not in seen, it is the first occurrence:
      • Add it to seen: seen.add(i).
      • Append it to result: result.append(i).
    • If i is already in seen, skip it.
  3. Return the result list, which now holds each unique element in the order of its first appearance.

Walk‑through with the example [1, 2, 2, 3, 1, 4]

StepElement iActionseenresult
11Not in seen → add & append{1}[1]
22Not in seen → add & append{1, 2}[1, 2]
32Already in seen → skip{1, 2}[1, 2]
43Not in seen → add & append{1, 2, 3}[1, 2, 3]
51Already in seen → skip{1, 2, 3}[1, 2, 3]
64Not in seen → add & append{1, 2, 3, 4}[1, 2, 3, 4]

Final result: [1, 2, 3, 4].

Back to Blog

Related posts

Read more »