In Python we can get the unique elements from a list by converting it to a set with set(). Sets are a
collection of unique elements:
Python
values = [1, 1, 1, 2, 2, 3, 3, 3, 3]
values = set(values)
print(values)Output:
Text
{1, 2, 3}And if we still need a list instead of a set, we can easily convert back to a list using list():
Python
values = [1, 1, 1, 2, 2, 3, 3, 3, 3]
# convert to set to get unique values
values = set(values)
# convert back to list
values = list(values)
print(values)Output:
Text
[1, 2, 3]
Warning
The order of elements after using
set() is not guaranteed. I wrote the examples in order to make it clear that duplicates were removed.I learned this trick after realizing that unfortunately Python doesn’t have a
uniq() method like Ruby that does this exact thing.
There are also other ways of getting unique values from a list that you can read about in
this GeeksforGeeks article. I didn’t cover the other cases because I feel like the easiest way is to use set().