DEV Community

Nelson Figueroa
Nelson Figueroa

Posted on • Originally published at nelson.cloud on

Get Unique Elements in a Python List

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:

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

values = set(values)

print(values)
Enter fullscreen mode Exit fullscreen mode

Output:

{1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

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

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)
Enter fullscreen mode Exit fullscreen mode

Output:

[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)