Skip to content
GreenSnippets

Remove duplicates but keep order

Deduplicate a list while preserving the first occurrence order, for hashable values or by key.

Python
def unique(items):
    return list(dict.fromkeys(items))


def unique_by(items, key):
    seen = set()
    result = []
    for item in items:
        k = key(item)
        if k not in seen:
            seen.add(k)
            result.append(item)
    return result

Example / expected output

Output
unique([3, 1, 3, 2, 1])  # [3, 1, 2]

How it works

list(set(x)) loses order. Since Python 3.7 dictionaries preserve insertion order, so dict.fromkeys is a one-liner for hashable items. The keyed version handles unhashable items such as dicts by tracking a derived key.