capypad
0 day streak
python / beginner
Snippet

Removing Duplicates with Sets

A set is a special data type in Python that only stores unique items. By converting a list into a set, Python automatically removes any duplicate values for you.

snippet.py
python
1
2
3
names = ["Alice", "Bob", "Alice", "Charlie"]
unique_names = set(names)
print(list(unique_names))
Breakdown
1
names = [...]
Creates a list containing a duplicate entry ('Alice').
2
unique_names = set(names)
Converts the list to a set, which forces all elements to be unique.
3
print(list(unique_names))
Converts the set back into a list and prints the result without duplicates.