Explain it simply
Explain it simply
Imagine taking attendance at a classroom door. If the same student walks in twice, you say "already counted" and skip them. That is deduplication.
Two questions decide how you do it. First, should the list stay in the order people arrived? Second, what does "the same" mean: are Sai and sai one person? Python offers several techniques, and the answers to those two questions tell you which one to pick. A third, quieter question is size: a method that feels instant on ten names can take minutes on a hundred thousand.
Problem → Why → Solution
The problem: set() scrambles order and crashes on lists
To remove repeated emails from a newsletter list, someone writes list(set(emails)). The duplicates disappear, but the signup order, where the earliest subscribers come first, is gone, and the order even changes between runs.
A week later each subscriber is stored as an [email, plan] list, and the same line crashes with TypeError: unhashable type: 'list'. Meanwhile Sai@mail.com and sai@mail.com are the same person, yet both survive.
emails = ["sai@mail.com", "aye@mail.com", "sai@mail.com", "Sai@mail.com"]
unique = list(set(emails))
print(unique) # order differs between runs; "Sai@" and "sai@" both stay
rows = [["sai@mail.com", "free"], ["sai@mail.com", "free"]]
list(set(rows)) # TypeError: unhashable type: 'list'Why does this happen?
A set is a hash table: it places items by their hash value and keeps no record of insertion order. String hashes are randomised per process for security, so the order can change from run to run. Hashing requires immutable items, which is why lists and dicts are rejected. And "the same" is decided by ==, so different letter case means different items.
Core concept: equality, order and hashability
Every piece of dedup code makes three decisions: how "the same" is checked (equality), what order the result has (order) and whether the items can be hashed (hashability). Since Python 3.7 a dict keeps insertion order as a language guarantee; a set makes no such promise. That single fact drives most of the choice between techniques.
| Technique | Order | Speed / limits |
|---|---|---|
| list(set(xs)) | Not guaranteed | O(n), hashable items only |
| list(dict.fromkeys(xs)) | First-seen order | O(n), hashable items only |
| seen set + loop | First-seen order | O(n), supports a key function |
| if x not in result | First-seen order | O(n²), works unhashable, slow |
1. Hashable items and order matters: dict.fromkeys()
dict.fromkeys(xs) inserts each item as a key. Inserting an existing key does not move it, so every item stays where it was first seen. It is one line and runs inside Python's C implementation.
2. Custom sameness: a key plus a loop
To compare emails after casefold(), or dict records by their id field only, compute key(item) and check it against a seen set. The original item goes into the result, so the display text is untouched.
3. Turn unhashable items into hashable keys
Use tuple(row) for lists, tuple(sorted(d.items())) or an id field for dicts. An if x not in result loop also works for unhashable items, but it rescans the whole result for every item, so ten thousand items can mean tens of millions of comparisons.
4. Remember that == is broader than it looks
Every hash-based technique relies on == and hash(). In Python 1 == 1.0 == True and their hashes match, so dict.fromkeys([1, 1.0, True]) returns just [1]. If values of different types must stay separate, use a key such as (type(x), x).
- Compute each item's key
- Look the key up in seen
- New key: record it, keep the item
- Known key: skip the item
dict.fromkeys() is this same model with the item as its own key; when you need a different key, write the loop.
General pattern
unique = list(dict.fromkeys(items)) # hashable, keep order
seen = set()
result = []
for item in items:
k = key_of(item) # e.g. item.casefold()
if k not in seen:
seen.add(k)
result.append(item)For plain hashable items the first line is enough. When you need a custom key or the items are unhashable, use the seen-set loop.
Example: the techniques side by side
The input [3, 1, 3, 2, 1, 5] is deliberately unsorted. With an already sorted input such as [1, 2, 2, 3], the set() result can happen to come out in order and hide the problem; here the difference is easy to see. The script also covers unhashable items and case-insensitive email addresses.
numbers = [3, 1, 3, 2, 1, 5]
print(f"Original: {numbers}")
# ===== 1. set(): unique, but order is not guaranteed =====
print(f"set(): {list(set(numbers))}")
# ===== 2. dict.fromkeys(): unique AND first-seen order =====
print(f"dict.fromkeys(): {list(dict.fromkeys(numbers))}")
# ===== 3. Loop with a 'seen' set: O(n), order kept =====
unique = []
seen = set()
for n in numbers:
if n not in seen:
seen.add(n)
unique.append(n)
print(f"seen-set loop: {unique}")
# ===== 4. Unhashable items (lists) =====
print("\n===== Unhashable items =====")
rows = [[1, 2], [3], [1, 2]]
try:
dict.fromkeys(rows)
except TypeError as error:
print(f"dict.fromkeys(rows) -> {type(error).__name__}")
unique_rows = [list(t) for t in dict.fromkeys(tuple(r) for r in rows)]
print(f"via tuple keys: {unique_rows}")
# ===== 5. Real world: case-insensitive emails =====
print("\n===== Case-insensitive emails =====")
emails = ["Sai@mail.com", "aye@mail.com", "sai@MAIL.com", "mya@mail.com"]
first_by_key = {}
for email in emails:
first_by_key.setdefault(email.casefold(), email)
print(f"Unique: {list(first_by_key.values())}")Code breakdown
- set() reorders
print(f"set(): {list(set(numbers))}")The result is [1, 2, 3, 5], not the original order [3, 1, 2, 5]. It looks sorted only because small ints hash to themselves in CPython; with strings the order can change on every run, so never rely on it.
- Order-preserving one-liner
print(f"dict.fromkeys(): {list(dict.fromkeys(numbers))}")A dict keeps keys in first-insertion order, giving 3, 1, 2, 5. The values are all None, but list() takes only the keys.
- Set lookup inside the loop
if n not in seen:seen is a set, so the in check is O(1) on average. Checking if n not in unique against a list instead scans the list for every item and becomes O(n²).
- Unhashable rows fail
dict.fromkeys(rows)rows contains lists, which cannot be dict keys, so TypeError is raised. The exact message text varies between Python versions, so the example prints only the exception type.
- Hashable stand-in key
unique_rows = [list(t) for t in dict.fromkeys(tuple(r) for r in rows)]Each list becomes a tuple for deduplication and then turns back into a list. Tuples are immutable, so they can be hashed.
- First original wins
first_by_key.setdefault(email.casefold(), email)The key is the casefolded text and the value is the original email. setdefault() only inserts a missing key, so the first spelling "Sai@mail.com" stays and "sai@MAIL.com" is skipped.
Original: [3, 1, 3, 2, 1, 5]
set(): [1, 2, 3, 5]
dict.fromkeys(): [3, 1, 2, 5]
seen-set loop: [3, 1, 2, 5]
===== Unhashable items =====
dict.fromkeys(rows) -> TypeError
via tuple keys: [[1, 2], [3]]
===== Case-insensitive emails =====
Unique: ['Sai@mail.com', 'aye@mail.com', 'mya@mail.com']Keep the first or the last occurrence?
Every technique in this lesson keeps the first occurrence. With records you often want the latest update instead: a user signs up on the free plan and later upgrades to pro, and the pro row should win.
The simple form is latest = {key(r): r for r in rows}. A repeated key overwrites the earlier value, so the last record survives, but the key keeps the position where it was first seen. If you also want the last position, pop() the key before inserting it again.
With a pandas DataFrame
When the data is already in pandas, skip the Python loop and call df.drop_duplicates(subset=["email"], keep="last"). subset picks the columns to compare and keep picks which row survives.
In real projects
In real projects
Deduplication shows up most when data is merged: contacts from two CSV exports, results collected from several API pages, orders submitted twice by a double-click. In that kind of data "the same" rarely means the whole object is equal; it means a business key matches, such as an email, an order id or a SKU.
For emails the key is usually computed with strip() and casefold(). You also have to decide what happens to empty or malformed emails: drop them, or collect them in a separate error list. In a database, a unique constraint is the final safeguard, because dedup code in Python cannot stop two concurrent requests from inserting the same row.
Common mistakes
Common mistakes
Writing a list comprehension for its side effects
[unique.append(x) for x in xs if x not in unique] works, but it builds a throwaway list full of None (append's return value), confuses readers and is O(n²) as well. Comprehensions are for building a new list; use a plain for loop for side effects.
Relying on the order of set()
Testing with a few small integers, the set() result often looks sorted, so it is easy to conclude it keeps order. Once string data arrives in production the order turns random. Use dict.fromkeys() when order matters, or write sorted(set(xs)) when you actually want sorted output.
Returning the normalised key instead of the item
list(dict.fromkeys(e.casefold() for e in emails)) removes duplicates but also throws away the spelling the user typed. Use the key only for comparing and store the original value.
Mini challenge
Write a reusable dedupe_by() function
Write dedupe_by(), which takes items, a key function and keep="first" or "last", and returns a list without duplicates. Test it on signup records keyed by casefolded email.
- keep="first" keeps the first occurrence, keep="last" keeps the last one
- Any other keep value raises ValueError
- With key=tuple it must work on input that contains lists
- Empty input returns an empty list
from typing import Callable, Hashable, Iterable, TypeVar
T = TypeVar("T")
def dedupe_by(items: Iterable[T], key: Callable[[T], Hashable],
keep: str = "first") -> list[T]:
"""Remove items whose key was already seen, keeping first or last."""
# TODO: reject keep values other than "first" and "last"
# TODO: map each key to the item you want to keep (a dict keeps order)
# TODO: for "last", make a repeated key move to the end
return []
signups = [
{"email": "sai@mail.com", "plan": "free"},
{"email": "Aye@mail.com", "plan": "free"},
{"email": "SAI@mail.com", "plan": "pro"},
]
# TODO: print the plans kept with keep="first" and keep="last"
# TODO: try key=tuple on [[1, 2], [3], [1, 2]] and on an empty listExpected: keep="first" gives ['free', 'free'], keep="last" gives ['free', 'pro'], the list input gives [[1, 2], [3]] and the empty input gives [].
Show hint
Use a dict from key to item. For "first", only insert keys that are missing. For "last", chosen.pop(k, None) and then insert again, which moves the key to the end.
Show solution
from typing import Callable, Hashable, Iterable, TypeVar
T = TypeVar("T")
def dedupe_by(items: Iterable[T], key: Callable[[T], Hashable],
keep: str = "first") -> list[T]:
"""Remove items whose key was already seen, keeping first or last."""
if keep not in ("first", "last"):
raise ValueError("keep must be 'first' or 'last'")
chosen: dict[Hashable, T] = {}
for item in items:
k = key(item)
if keep == "last":
chosen.pop(k, None) # move the key to the end
chosen[k] = item
elif k not in chosen:
chosen[k] = item
return list(chosen.values())
signups = [
{"email": "sai@mail.com", "plan": "free"},
{"email": "Aye@mail.com", "plan": "free"},
{"email": "SAI@mail.com", "plan": "pro"},
]
def by_email(row: dict) -> str:
return row["email"].casefold()
print([r["plan"] for r in dedupe_by(signups, by_email)])
print([r["plan"] for r in dedupe_by(signups, by_email, keep="last")])
print(dedupe_by([[1, 2], [3], [1, 2]], key=tuple))
print(dedupe_by([], key=str))Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- set() is fast but makes no ordering promise; dict.fromkeys() keeps first-seen order
- For a custom key such as casefold or an id field, loop with a seen set and keep the original item
- Convert unhashable items to hashable keys, such as tuples, before deduplicating
- A loop with if x not in list is O(n²); avoid it for large data
The Python Tutorial — Python Software Foundation