Counting occurrences with collections.Counter
suggest changefrom collections import Counter
c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"])
c
# Out: Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2})
c["a"]
# Out: 3
c[7] # not in the list (7 occurred 0 times!)
# Out: 0
The collections.Counter can be used for any iterable and counts every occurrence for every element.
When initialized from a dict or another collections.abc.Mapping, Counter treats the mapping's values as existing counts rather than counting its keys:
Counter({"e": 2})
# Out: Counter({"e": 2})
Counter({"e": "e"}) # Counter does not validate that counts are integers.
# Out: Counter({"e": "e"})
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents