Essay record

Python: Remove duplicate list items with a set

Record
Essay / / 1 min read / 96 words
On this page3 sections / +

DISCLOSURE: Some links may be affiliate links. Details

problem

In my Python program I have a list containing duplicate elements. How can I easily get rid of those duplicates?

solution

There are tons of possible ways to do this, but one simple way to dedupe a list is to use an intermediate set. Here's an example:

list_with_duplicates = [ "a", "b", "a"]
set_without_duplicates = set(list_with_duplicates)
list_without_duplicates = list(set_without_duplicates)

print(list_without_duplicates)

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Built with CloudSeed Rust