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:
|
|
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()
:
|
|
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()
.