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:
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.
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:
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:
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:
References:
set: https://docs.python.org/3/library/stdtypes.html#set
List Comprehensions: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
dict.fromkeys: https://docs.python.org/3/library/stdtypes.html#dict.fromkeys
collections.Counter: https://docs.python.org/3/library/collections.html#collections.Counter
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!