download

Remove duplicates from a list but keep the original order

Python~10 minReviewed 29 Oct 2026Free · No sign-in

Question

Write dedupe(items, key). It removes duplicates, keeps the first copy of each item, and keeps the original order. key turns an item into the value you compare. By default it is the item itself.

"PYTHON"
dedupe([3, 1, 3, 2, 1])  # [3, 1, 2]

tickets = [{"id": "Q4", "version": 1}, {"id": "K2", "version": 1},
           {"id": "Q4", "version": 2}, {"id": "N7", "version": 1}]
dedupe(tickets, key=lambda t: t["id"])  # Q4 v1, K2 v1, N7 v1

Then explain why list(set(items)) doesn't work here.

"CODE · PYTHON"
def dedupe(items, key=lambda item: item):
    ...
Show hints (3)
  1. "ONE QUESTION PER ITEM"

    Walk the list once, from left to right. For each item you only need to answer one question: have I seen its key before?

  2. "TWO STRUCTURES"

    A set answers "seen before?" in O(1) on average. A list keeps the order. Use both: the set for checking, the list for the result.

  3. "THE LOOP"

    For each item, compute item_key = key(item). If it is not in seen, add it to seen and append the item to the result. Otherwise skip the item.

Show checked explanation

Walk the list once and keep a set of the keys you have seen. Append an item to the result only the first time its key appears. That is O(n). When the items are their own keys, list(dict.fromkeys(items)) does it in one line, because dicts keep insertion order (guaranteed since Python 3.7). A set keeps no order.

"SOLUTION · PYTHON"
def dedupe(items, key=lambda item: item):
    seen = set()
    result = []
    for item in items:
        item_key = key(item)
        if item_key not in seen:
            seen.add(item_key)
            result.append(item)
    return result


print(dedupe([3, 1, 3, 2, 1]))
tickets = [{"id": "Q4", "version": 1}, {"id": "K2", "version": 1},
           {"id": "Q4", "version": 2}, {"id": "N7", "version": 1}]
kept = dedupe(tickets, key=lambda t: t["id"])
print([(t["id"], t["version"]) for t in kept])
"OUTPUT"
[3, 1, 2]
[('Q4', 1), ('K2', 1), ('N7', 1)]

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Here are the tickets with key=lambda t: t["id"]:

ticketkeyseen before?result after this step
Q4 v1Q4noQ4 v1
K2 v1K2noQ4 v1, K2 v1
Q4 v2Q4yes, skipQ4 v1, K2 v1
N7 v1N7noQ4 v1, K2 v1, N7 v1

Each structure has one job. The set only answers "have I seen this key?". The list holds the result. You fill it while you walk the input, so it keeps the input order.

Now look at list(set(items)). It fails here for two reasons. First, a set has no order you can rely on. In CPython, list(set([3, 1, 3, 2, 1])) gives [1, 2, 3], not [3, 1, 2]. Second, dicts can't go into a set, so set(tickets) raises TypeError: unhashable type: 'dict'.

The key decides what "duplicate" means. With key=lambda t: t["id"], Q4 v2 is a duplicate of Q4 v1. With key=lambda t: (t["id"], t["version"]), it is not, and all four tickets stay. The rule decides which data you lose, so ask which rule is wanted before you write code.

The result holds the same dict objects as the input, not copies. If you change a ticket later, the result shows the change.

Set lookups are O(1) on average, so the whole pass is O(n). The set holds one entry per distinct key, so it needs O(n) memory in the worst case.

Common mistakes

  • Checking if item not in result on the result list. It gives the right answer, but each check scans the whole list, so the pass becomes O(n²).
  • Forgetting that 1, 1.0 and True are equal and have the same hash. dedupe([1, True, 1.0]) returns [1]. If the type matters, use key=lambda x: (type(x), x). Then all three stay.
  • Using a list or dict as the key. Keys go into a set, so they must be hashable, and a list key raises TypeError. Turn it into a tuple first: key=lambda t: tuple(t["tags"]).

Follow-up questions

  • "Keep the last version of each ticket instead." Build a dict keyed by id and let later tickets overwrite earlier ones: latest = {t["id"]: t for t in tickets}. Overwriting a key doesn't move it, so each id keeps its first position but holds its last ticket. Here that gives Q4 v2, K2 v1, N7 v1.
  • "What if two different keys have the same hash?" Nothing breaks. A set uses the hash to find where to look, then compares the keys with ==. Equal hashes alone don't make two keys duplicates. They only make lookups slower.
  • "The input is too big for the set to fit in memory." For exact results, keep the seen keys outside the process, for example in a database table with a unique index on the key. A Bloom filter uses far less memory. It never misses a real duplicate, but it sometimes says "seen" for a new key. Then you drop an item that is not a duplicate.

What a strong answer covers

Asks what counts as a duplicate before coding. Uses a set for checks and a list for order, and explains why list(set(items)) fails. Knows dict.fromkeys and the 1 == 1.0 == True trap.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from The Python Interview Handbook (Nezir Zahirovic, 2023); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.