Sentry Answers>Python>

Get unique values from a list in Python

Get unique values from a list in Python

David Y.

The ProblemJump To Solution

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:

Click to Copy
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:

Click to Copy
my_list = [3, 1, 2, 3, 2, 1] uniques = list(dict.fromkeys(my_list)) print(uniques) # will output [3, 1, 2]
  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Sentry BlogLogging in Python: A Developer’s Guide
  • logo
    Listen to the Syntax Podcast

    Tasty Treats for Web Developers brought to you by Sentry. Web development tips and tricks hosted by Wes Bos and Scott Tolinski

    Listen to Syntax

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.

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