Lists and algorithms · beginner
Python Program to Remove Duplicates from a List
Remove duplicate items from a Python list while keeping the original order, with a loop and a set, with dict.fromkeys(), and know when set() is enough.
- sets
- dict.fromkeys()
- list.append()
- membership test in
set(items) removes duplicates in one call, but it does not keep the order of the items. Most of the time you want the first occurrence of each item, in its original position, so the program uses a set only to remember what it has already seen.
The program
items = ["apple", "banana", "apple", "cherry", "banana", "date"]
seen = set()
unique = []
for item in items:
if item not in seen:
seen.add(item)
unique.append(item)
print(unique)
print(list(dict.fromkeys(items)))['apple', 'banana', 'cherry', 'date']
['apple', 'banana', 'cherry', 'date']How it works
- seen is a set of items already added. Checking item in seen is fast even for large lists.
- The first time an item appears it is added to both seen and unique; later copies fail the test and are skipped.
- unique keeps the items in the order they first appeared.
- dict.fromkeys(items) does the same in one line: dictionary keys are unique and keep insertion order (guaranteed since Python 3.7).
Watch it run line by line
Watch seen and unique side by side: on the second "apple" the if line runs but the highlighted line jumps straight back to the for, and neither variable changes.
“Visualize step by step” opens the program in the Python Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: When order does not matter
set() is the shortest way. Sort the result if you need a predictable order, because the order of a set is not guaranteed.
numbers = [3, 1, 3, 2, 1]
print(sorted(set(numbers)))
print(len(numbers) - len(set(numbers)), "duplicates removed")[1, 2, 3]
2 duplicates removedCommon mistakes
- Removing items from the list while looping over it with for: the loop skips elements and some duplicates survive.
- Checking item not in unique (a list) instead of a set: correct, but slow for long lists because each check scans the whole list.
- Using set() on a list of lists or dictionaries raises TypeError: unhashable type. Convert inner lists to tuples first.
Try it yourself
- Remove duplicates while ignoring case, so "Apple" and "apple" count as the same item.
- Print only the items that appear more than once.
Open the program in the Python Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 Python examples, or write your own program in the online Python Compiler.