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:

1
2
3
4
5
values = [1, 1, 1, 2, 2, 3, 3, 3, 3]

values = set(values)

print(values)

Output:

{1, 2, 3}

And if we still need a list instead of a set, we can easily convert back to a list using list():

1
2
3
4
5
6
7
8
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:

[1, 2, 3]

I learned this trick after realizing that unfortunately Python doesn’t have a uniq() method like Ruby that does this exact thing.

There’s 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().

References