Counters
Counter is a class from the collections module designed for counting hashable objects. It is a subclass of dict where elements are keys and their counts ar...
What is Counter?
Counter is a class from the collections module designed for counting hashable objects. It is a subclass of dict where elements are keys and their counts are values. from collections import Counter; c = Counter("mississippi") counts each character: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1}). You can also initialise from a list: Counter([1, 2, 2, 3, 1, 1]) gives Counter({1: 3, 2: 2, 3: 1}). Accessing a missing key returns 0, unlike a regular dict which raises KeyError.
Counter Methods
most_common(n) returns the n most frequent elements as a list of (element, count) tuples, sorted by count descending. c.most_common(3) on a word-count counter returns the top 3 words. elements() returns an iterator over elements repeated by their count: list(Counter("aab").elements()) gives ["a", "a", "b"]. subtract(other) subtracts counts (counts can go negative). update(other) adds counts — different from dict.update() which replaces.
Arithmetic with Counters
Counter objects support +, -, &, and | operations. Counter("aab") + Counter("bbc") gives Counter({"b": 3, "a": 2, "c": 1}). Subtraction with - discards zero and negative counts. & (intersection) takes the minimum of counts; | (union) takes the maximum. These operations make Counter very powerful for multiset arithmetic — for example, finding the inventory surplus or shortage between two stock counts by subtracting one Counter from another.
Practical Use Case
Counting word frequencies in a text: words = text.lower().split(); freq = Counter(words); print(freq.most_common(10)) prints the 10 most common words. Checking if one string is an anagram of another: Counter("listen") == Counter("silent") returns True because both produce the same character counts. Finding characters in common: Counter("abcde") & Counter("cdexyz") gives Counter({"c": 1, "d": 1}). Counter eliminates most manual counting loops.
Worked Example: Anagram Check
def is_anagram(s1, s2): return Counter(s1.lower()) == Counter(s2.lower()). This is clean, readable, and correct. The alternative without Counter involves sorting: sorted(s1.lower()) == sorted(s2.lower()), which is O(n log n). The Counter approach is O(n) because building and comparing two hash tables is linear. For interview problems about frequency counting, Counter is almost always the best tool and signals Python proficiency.
Exam Tip
Know that Counter is imported from collections, not the standard namespace. What does Counter("hello")["z"] return? 0 — not KeyError. This zero-default is Counter's most useful property for frequency logic. What does Counter("aab") - Counter("ab") give? Counter({"a": 1}) — subtraction removes zero and negative counts. Common interview question: given a list of integers, find the element that appears most often. The one-liner: Counter(lst).most_common(1)[0][0] is clean and correct.