Lists
How to count occurrences in a list in Python
Quick answer
Use a dict to count occurrences in a list with {x: my_list.count(x) for x in set(my_list)}.
my_list = [1, 2, 2, 3, 3, 3]
occurrences = {x: my_list.count(x) for x in set(my_list)}
print(occurrences)This snippet counts occurrences of each item in a list by using a dict comprehension. It works by iterating over a set of unique items in the list, then using the count method to get the number of occurrences for each item. This approach is straightforward but not efficient for large lists because the count method has to scan the list for each item.
A more efficient approach would be to use a dict and iterate over the list only once, incrementing the count for each item as we go.
Variations
Using collections.Counter
from collections import Counter
my_list = [1, 2, 2, 3, 3, 3]
occurrences = Counter(my_list)
print(occurrences)more efficient
Handling empty lists
my_list = []
occurrences = {x: my_list.count(x) for x in set(my_list)} if my_list else {}
print(occurrences)avoid KeyError
Counting occurrences in a list of strings
my_list = ['a', 'b', 'b', 'c', 'c', 'c']
occurrences = {x: my_list.count(x) for x in set(my_list)}
print(occurrences)case sensitive
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.