Get unique values from a list in Python

David Y.

The Problem

How do I get all of the unique values in a Python list? In other words, how do I remove duplicates from a list?

The Solution

We can get all the unique values in a Python list by converting the list into a set, which is an unordered data structure with no duplicate elements. Consider the code below:

my_list = [3, 1, 2, 3, 2, 1] uniques = set(my_list) print(uniques) # will output {1, 2, 3}

From there, we can convert the set back into a list using list(uniques).

This method does not preserve the list’s original order. If the order is important, we will need to use a less orthodox approach to the problem. Like values in sets, Python dictionary keys must be unique, and since version 3.7, Python preserves the insertion order of dictionary keys. Therefore, we can get the unique values in our list by converting its values to dictionary keys using dict.fromkeys. From there, we convert back to a list. See below:

my_list = [3, 1, 2, 3, 2, 1] uniques = list(dict.fromkeys(my_list)) print(uniques) # will output [3, 1, 2]

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key>@sentry.io/<project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.