How to Count Unique Values in a Python List?

Estimated read time 2 min read

There are several ways to count unique values in a Python list. Here are a few methods:

  1. Using a Set:
my_list = [1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 7]
unique_values = set(my_list)
count = len(unique_values)
print(count)  # Output: 7

In this approach, we convert the list to a set, which automatically removes duplicate values, since sets only allow unique elements. Then, we use the len() function to get the count of unique values.

  1. Using a Dictionary:
my_list = [1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 7]
unique_dict = {}
for value in my_list:
    unique_dict[value] = True
count = len(unique_dict)
print(count)  # Output: 7

In this approach, we iterate through the list and use a dictionary to keep track of unique values as keys. Since dictionary keys are unique, this approach allows us to count the unique values. We then use the len() function to get the count of unique values.

  1. Using the Counter class from the collections module:
from collections import Counter

my_list = [1, 2, 3, 3, 4, 4, 5, 6, 6, 7, 7, 7]
count_dict = Counter(my_list)
count = len(count_dict)
print(count)  # Output: 7

In this approach, we use the Counter class from the collections module, which is specifically designed for counting elements in collections. We pass the list to the Counter class, which returns a dictionary-like object with elements as keys and their counts as values. We then use the len() function to get the count of unique values, which is the length of the Counter object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply