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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs