How to count unique values in the list

Just use the 'counter' class from the collections package.

Counter returns collections like dictionary object. Keys in this collection are elements of the list and values are counts of each element in the list. But there is one peculiarity. If we try to access a non-existent key, we will get 0, not an error.

from collections import Counter

my_list = [1, 1, 3, 4, 4, 5, 3, 4, 2, 11]

count_dict = Counter(my_list)
print(count_dict)

print(f"The list has {count_dict[4]} number 4.")

print(f"The list has {count_dict[13]} number 13.")

Output:

Counter({4: 3, 1: 2, 3: 2, 5: 1, 2: 1, 11: 1})
The list has 3 number 4.
The list has 0 number 13.

How to get all unique values count? Use: len(count_dict).

#python
0
Roman Ivashchenko profile picture
Nov 24, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related