Thuta Learning
Python
AdvancedProgrammingBeginner

Remove Duplicates (Enhanced)

PythonLesson 5625 min

What you'll walk away with

  • Explain why set() makes no ordering promise while dict.fromkeys() keeps first-seen order
  • Deduplicate lists that contain unhashable items such as lists or dicts without a TypeError
  • Compare values like emails through a casefold() key while keeping the original text
  • Tell an O(n²) "if x not in list" loop apart from an O(n) seen-set loop

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.

subscribers.py
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.

TechniqueOrderSpeed / limits
list(set(xs))Not guaranteedO(n), hashable items only
list(dict.fromkeys(xs))First-seen orderO(n), hashable items only
seen set + loopFirst-seen orderO(n), supports a key function
if x not in resultFirst-seen orderO(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).

Mental model: a doorkeeper with a notebook
  1. Compute each item's key
  2. Look the key up in seen
  3. New key: record it, keep the item
  4. 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

python
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.

dedupe.py
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

  1. set() reordersprint(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.

  2. Order-preserving one-linerprint(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.

  3. 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²).

  4. 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.

  5. Hashable stand-in keyunique_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.

  6. 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.

You should see
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
dedupe_by.py
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 list

Expected: 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
dedupe_by.py
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

What does list(dict.fromkeys(["b", "a", "b", "c", "a"])) return?

Quick quiz 2 / 3

With rows = [[1, 2], [1, 2]], what happens on list(set(rows))?

Quick quiz 3 / 3

You must dedupe a list of 50,000 strings and keep their order. Which approach fits best?

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Remove Duplicates (Enhanced) | Thuta Learning