python / beginner
Snippet
Finding Unique Items with Sets
In Python, a set is a collection that does not allow duplicate values. Converting a list into a set is the easiest way to remove all duplicates instantly.
snippet.py
1
2
3
numbers = [1, 2, 2, 3, 4, 4, 5]unique_numbers = set(numbers)print(unique_numbers)
Breakdown
1
numbers = [1, 2, 2, 3, 4, 4, 5]
Creates a list containing several duplicate integers.
2
unique_numbers = set(numbers)
Passes the list to the set() constructor to filter out duplicates.
3
print(unique_numbers)
Displays the result, showing only unique values {1, 2, 3, 4, 5}.