How to remove duplicates from a list in Python

Remove duplicates from a Python list and keep the original order, with dict.fromkeys, a set and a loop. Run every example in your browser.

Short answer

Use list(dict.fromkeys(items)). It removes repeats and keeps the first copy of each item in its original order, in one pass. list(set(items)) is also short, but it does not keep the order.

Method 1: dict.fromkeys (keeps order)

A dictionary cannot hold the same key twice, and since Python 3.7 it remembers the order keys were added. So building a dict from the list and turning its keys back into a list drops the repeats and keeps the first copy of each item where it was.

items = [3, 1, 3, 2, 1]
unique = list(dict.fromkeys(items))
print(unique)
Output
[3, 1, 2]

Method 2: a loop with a set (keeps order, easy to explain)

This is the version interviewers like, because every step is visible. The set answers “have I seen this already?” in one step, so the whole function stays O(n).

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

print(remove_duplicates(["A7", "B2", "A7", "C1"]))
Output
['A7', 'B2', 'C1']

Method 3: set (fastest to type, order not kept)

A set keeps one copy of each value, but it has no order of its own. Use it when order does not matter, for example when you only need the distinct values or their count.

items = [3, 1, 3, 2, 1]
print(len(set(items)))
print(sorted(set(items)))
Output
3
[1, 2, 3]

Common mistakes

  • Checking if item not in result on the output list. It works, but a list check scans from the front, so the function becomes O(n²) and slows down badly on long lists. Check a set instead.
  • Expecting list(set(items)) to keep the order. Sometimes it looks sorted for small numbers, but that is an accident of how integers hash. Do not rely on it.
  • Using a set or dict.fromkeys on a list of lists. Lists cannot be dict keys, so Python raises TypeError: unhashable type: 'list'. Convert each inner list to a tuple first (see the FAQ).

Practice: your turn

A shopping cart can list the same product more than once. Write solve(items) that returns the product IDs with repeats removed, keeping the first copy of each ID in its original order. Aim for O(n).

This challenge and its tests come from the PyMaster course. Press Run tests to check your function.

main.py
Input for input()

Runs real Python 3.14 in your browser with Pyodide. Your code is not uploaded. Ctrl + Enter runs the tests. Press Esc, then Tab, to leave the editor.

Hint 1

Walk the list once and build a new list as you go.

Hint 2

Checking the output list is the slow part. Keep a second structure that answers “seen it?” quickly.

Hint 3

Keep a set of IDs already added. Skip an ID found in the set; otherwise add it to the set and to the output.

Show a solution
def solve(items):
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

Questions

Does list(set(my_list)) keep the order?

No. A set has no defined order, so the result can come back in any order. Use list(dict.fromkeys(my_list)) when order matters.

How do I remove duplicates from a list of lists?

Turn each inner list into a tuple so it can be hashed, remove the repeats, then turn them back: list(map(list, dict.fromkeys(map(tuple, rows)))).

How do I remove duplicates in place, without a new variable?

Assign to a full slice: items[:] = dict.fromkeys(items). Every other name that points to the same list sees the change.

Which method is fastest?

dict.fromkeys and set both run in O(n) and are implemented in C, so they beat a hand-written loop. The loop is still O(n) and is the one to write in an interview.

More Python programs

  • Count how many times each character appears in a string in Python

    Count the frequency of each character in a Python string with a dict, collections.Counter and str.count, and find the most common one. Run it in your browser.

  • Palindrome program in Python

    Check if a string or a number is a palindrome in Python with slicing, two pointers and a loop, and ignore spaces and case. Run every example in your browser.

  • Fibonacci series in Python

    Print the Fibonacci series in Python with a for loop, a while loop, recursion and a generator, and find the nth Fibonacci number. Run every example in your browser.

All Python programs Online Python compiler