How to get unique values from a list in Python


There are various ways in which you can get unique values from a list in Python.

Let's take a look at a few examples.


Example 1: Using set
number_list = [4, 2, 1, 4, 3, 2]

unique_values = list(set(number_list))

print(unique_values)
Output:

[1, 2, 3, 4]

In the above example, we converted the list to a set and then back to a list to get the list of unique numbers.

Note: The output is a order list of unique values.

This is the best approach as set has an average time complexity of O(1)


Example 2: Using a list comprehension
number_list = [4, 2, 1, 4, 3, 2]

unique_values = [no for i, no in enumerate(number_list) if no not in number_list[:i]]

print(unique_values)
Output:

[4, 2, 1, 3]

Note: This will provide a list that is in order and has unique values.


Example 3: Using dict.fromkeys
number_list = [4, 2, 1, 4, 3, 2]

unique_values = list(dict.fromkeys(number_list))

print(unique_values)
Output:

[4, 2, 1, 3]

Note: This will provide a list that is in order and has unique values.


Example 4: Using collections module
from collections import Counter

city_list = [
    "Tokyo", "London", "New York", "Paris", "Sydney",
    "Cairo", "Tokyo", "Beijing", "New York", "Moscow",
    "Rio de Janeiro", "London", "Sydney", "Mumbai", "Lima"
]

city_counts = Counter(city_list)
unique_cities = [city for city, count in city_counts.items() if count == 1]

print(unique_cities)
Output:

['Paris', 'Cairo', 'Beijing', 'Moscow', 'Rio de Janeiro', 'Mumbai', 'Lima']



Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap