{ }codelper

Reference › Python

Python: Remove Duplicates from a List

How you remove duplicate values depends on whether you need to keep the order. If the order doesn't matter, use set(). To keep the order in which values first appear, use dict.fromkeys(). Both go through the list only once, so they are fast.

list(set(items))             # order is not guaranteed
list(dict.fromkeys(items))   # order of first appearance

set: when the order doesn't matter

A set holds each value only once. Turn a list into a set and the duplicates are gone. But a set has no order, so you must not rely on the order you get when you turn it back into a list. Use it when you only need the number of different values, or when you are going to sort anyway.

nums = [3, 1, 3, 2, 1, 3]print(len(set(nums)))print(sorted(set(nums)))print(sorted(set("mississippi")))
Output
3
[1, 2, 3]
['i', 'm', 'p', 's']

Edit and run it →

dict.fromkeys: keep the order of first appearance

Dictionary keys cannot repeat, and they keep the order in which they were added (since Python 3.7). Put the values in as keys with dict.fromkeys(items), take them back out as a list, and only the duplicates are dropped. The order of first appearance stays the same.

names = ["lee", "kim", "lee", "park", "kim"]unique = list(dict.fromkeys(names))print(unique)print(dict.fromkeys(names))
Output
['lee', 'kim', 'park']
{'lee': None, 'kim': None, 'park': None}

Edit and run it →

As the second line shows, fromkeys builds a dictionary whose values are all None. Here you only use the keys.

With a loop: when you decide what counts as the same

When you have your own rule, such as treating words as the same even if their case differs, loop yourself. Record each key you have already seen in a set, and add an item to the result only the first time you see its key.

words = ["Apple", "apple", "Kiwi", "APPLE", "kiwi"]seen = set()result = []for w in words:    key = w.lower()    if key not in seen:        seen.add(key)        result.append(w)print(result)
Output
['Apple', 'Kiwi']

Edit and run it →

You could search the result list directly with if w not in result and get the same answer. But a list is searched from the start every time, so it gets much slower as the values grow. Leave the searching to a set.

Removing duplicates from a list of lists

You can't put a list into a set or use it as a dictionary key. Turn each inner list into a tuple, remove the duplicates, then turn them back into lists.

pairs = [[1, 2], [3, 4], [1, 2], [2, 1]]unique = [list(t) for t in dict.fromkeys(tuple(p) for p in pairs)]print(unique)
Output
[[1, 2], [3, 4], [2, 1]]

Edit and run it →

[1, 2] and [2, 1] are in a different order, so they stay as different values.

Are there duplicates, and which values repeat?

If you only want to know whether there are duplicates, without removing them, convert to a set and compare the lengths. To find which values repeat, count them with Counter.

from collections import Counter nums = [3, 1, 3, 2, 1, 3]print(len(nums) != len(set(nums)))dup = [x for x, c in Counter(nums).items() if c > 1]print(dup)
Output
True
[3, 1]

Edit and run it →

Common mistakes

Relying on the order of list(set(...))

names = ["lee", "kim", "lee", "park"]
print(list(set(names)))

→ lee, kim and park are all there, but the order is not fixed. With strings it can change every time you run the program

Even if it happens to come out right on your computer, it can be marked wrong when graded. If the order matters, use list(dict.fromkeys(names)). If you want sorted order, use sorted(set(names)).

Putting a list of lists into a set

pairs = [[1, 2], [1, 2]]
print(set(pairs))

→ TypeError: unhashable type: 'list'

A set can only hold values that cannot change. Turn the inner lists into tuples, as in set(tuple(p) for p in pairs).

1, 1.0 and True are merged into one

values = [1, 1.0, True, "1", 0, False]
print(list(dict.fromkeys(values)))

→ Of the six values, only three are left: [1, '1', 0]

In Python 1 == 1.0 == True and 0 == False, so they count as the same value (the string "1" is different). To tell the types apart too, filter with a loop and use (type(v), v) as the key.

Practice problems

See also