Python - Unique values count of each Key

When it is required to find unique values count of every key, we can use several approaches including iteration with the 'append' method, the set() function, or dictionary-based counting methods.

Using Iteration with Append Method

This approach manually tracks unique values by checking if each element already exists in a filtered list ?

my_list = [12, 33, 33, 54, 84, 16, 16, 16, 58]

print("The list is :")
print(my_list)

filtered_list = []
elem_count = 0

for item in my_list:
    if item not in filtered_list:
        elem_count += 1
        filtered_list.append(item)

print("The result is :")
print(elem_count)
The list is :
[12, 33, 33, 54, 84, 16, 16, 16, 58]
The result is :
6

Using set() Function

The most efficient way to count unique values is using Python's built-in set() function ?

my_list = [12, 33, 33, 54, 84, 16, 16, 16, 58]

print("The list is :")
print(my_list)

unique_count = len(set(my_list))

print("The result is :")
print(unique_count)
The list is :
[12, 33, 33, 54, 84, 16, 16, 16, 58]
The result is :
6

Using Counter for Individual Value Counts

To see the count of each unique value, use Counter from the collections module ?

from collections import Counter

my_list = [12, 33, 33, 54, 84, 16, 16, 16, 58]

print("The list is :")
print(my_list)

value_counts = Counter(my_list)
print("Count of each unique value :")
print(dict(value_counts))

print("Total unique values :")
print(len(value_counts))
The list is :
[12, 33, 33, 54, 84, 16, 16, 16, 58]
Count of each unique value :
{12: 1, 33: 2, 54: 1, 84: 1, 16: 3, 58: 1}
Total unique values :
6

Comparison

Method Time Complexity Best For
Manual Iteration O(n²) Learning purposes
set() Function O(n) Just counting unique values
Counter O(n) Individual value counts

Conclusion

Use len(set(my_list)) for the most efficient way to count unique values. Use Counter when you need individual counts for each unique value.

Updated on: 2026-03-26T02:09:25+05:30

442 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements