Introduction
Counter is a dict subclass for counting hashable objects, useful for frequency analysis.
Basic Counter
from collections import Counter
# From list
c = Counter(["a", "b", "a", "c", "a"])
print(c) # Counter({'a': 3, 'b': 1, 'c': 1})
# From string
c = Counter("hello world")
print(c) # Counter({'l': 3, 'o': 2, 'h': 1, ...})
# From dictionary
c = Counter({"a": 3, "b": 1})
Counter Methods
c = Counter([1, 2, 2, 3, 3, 3])
c.elements() # Iterator over elements
c.most_common(2) # Top 2 most common
c.most_common() # All sorted by count
c.total() # Sum of all counts
# Arithmetic
c1 = Counter([1, 2, 2])
c2 = Counter([2, 3, 3])
c1 + c2 # Counter addition
c1 - c2 # Subtraction (positive only)
c1 & c2 # Intersection (min)
c1 | c2 # Union (max)
Practice Problems
- Count character frequency in string
- Find most common words in text
- Compare two lists using Counter
- Create histogram with Counter
- Track letter occurrences in word