Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Count Frequencies of Elements Using collections.Counter in Python

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips

collections.Counter is similar to a dict object. You can iterate through it similarly to how you iterate through a dict.

from collections import Counter

x = [1, 2, 3, 4, 5, 5, 4, 3, 3]
cntr = Counter(x)
cntr
Counter({1: 1, 2: 1, 3: 3, 4: 2, 5: 2})
cntr.items()
dict_items([(1, 1), (2, 1), (3, 3), (4, 2), (5, 2)])
cntr.values()
dict_values([1, 1, 3, 2, 2])
cntr.values()
dict_values([1, 1, 3, 2, 2])