Counter Class in Python: Usage & Examples

How-to basics · Updated November 22, 2026

The Counter class in Python is a specialized dictionary from the collections module that counts hashable objects, making it the fastest and most readable way to tally frequencies in a collection. You create one by passing an iterable, a mapping, or keyword arguments to Counter(), then access counts like dictionary values, with the added benefit of methods like most_common() and arithmetic operations. It is part of the standard library, so no installation is needed—just from collections import Counter.

What Is Counter and Why Use It?

Before Counter, counting elements in a list meant writing a loop with a dictionary and checking if item in counts or using dict.get(). Counter wraps that logic into a clean, efficient object. It is a subclass of dict, so it inherits all normal dictionary methods (keys(), values(), items(), update(), etc.) but adds counting-specific functionality. The underlying implementation is optimized in C, so it is typically faster than a manual loop for large datasets. You should use it whenever you need to count occurrences—word frequencies, survey responses, inventory items, or even characters in a string.

Creating a Counter

There are several ways to instantiate a Counter, and the choice depends on your data source:

  • From an iterable (list, tuple, string): Counter(['a', 'b', 'a']) gives Counter({'a': 2, 'b': 1}).
  • From a dictionary: Counter({'a': 2, 'b': 1}) preserves the counts.
  • From keyword arguments: Counter(a=2, b=1) is equivalent.
  • From nothing: Counter() creates an empty counter; you add counts later with update().

For a string, Counter('hello') counts characters: Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1}). Note that Counter only works with hashable elements—lists and dictionaries cannot be counted directly because they are unhashable.

Key Methods and Operations

Beyond dictionary methods, Counter provides several unique tools:

  • most_common([n]): Returns a list of the n most common elements and their counts, sorted from highest to lowest. Without n, it returns all elements.
  • elements(): Returns an iterator that repeats each element as many times as its count, in arbitrary order. For example, list(Counter({'a': 2, 'b': 1}).elements()) yields ['a', 'a', 'b'].
  • subtract(iterable_or_mapping): Subtracts counts from another counter or iterable, allowing counts to go negative.
  • update(iterable_or_mapping): Adds counts from another source, rather than replacing them like a normal dictionary update.
  • total() (Python 3.10+): Returns the sum of all counts. For older versions, use sum(counter.values()).

Accessing a missing key returns 0 instead of raising a KeyError—a major convenience. For example, c = Counter('ab'); c['z'] returns 0.

Arithmetic and Set Operations

One of the most powerful features is that Counter supports mathematical operations with other counters or integers:

  • c1 + c2: Adds counts, keeping only positive counts.
  • c1 - c2: Subtracts counts, keeping only positive results.
  • c1 & c2: Intersection—takes the minimum count for each element.
  • c1 | c2: Union—takes the maximum count for each element.
  • +c and -c: Unary plus returns a counter with only positive counts; unary minus returns only negative counts.

These operations are useful for comparing word frequencies across documents or managing inventory. For example, Counter({'a': 3, 'b': 1}) - Counter({'a': 1, 'b': 2}) yields Counter({'a': 2}) because b goes to -1 and is discarded.

Common Use Cases and Examples

Here are three practical scenarios where Counter shines:

  1. Word frequency in a text: words = text.split(); word_counts = Counter(words); top_three = word_counts.most_common(3).
  2. Finding the most common element: Counter(my_list).most_common(1)[0][0] gives the mode.
  3. Merging counts from multiple sources: c = Counter(); c.update(list1); c.update(list2) accumulates totals.

For a concrete example, suppose you have a list of survey responses: responses = ['yes', 'no', 'yes', 'maybe', 'yes']. Counter(responses) returns Counter({'yes': 3, 'no': 1, 'maybe': 1}). Calling most_common(1) gives [('yes', 3)].

Performance and Limitations

Counter is generally faster than manual loops because it is implemented in C and uses a specialized counting algorithm. However, it does have limitations:

  • Memory: It stores every unique element as a key, so for extremely large cardinalities (e.g., millions of unique words), memory usage can be high.
  • Hashability: Only hashable objects can be counted. Lists, dictionaries, and sets are not allowed.
  • Order: Before Python 3.7, dictionaries were unordered, so Counter order was arbitrary. Since 3.7, insertion order is preserved, but most_common() sorts by count, not insertion.
  • Negative counts: After subtract(), counts can be negative, which may surprise users expecting only non-negative values.

If you need to count elements in a stream without storing all unique items, consider using collections.defaultdict(int) or a streaming algorithm, but for most batch tasks, Counter is the right choice.

Frequently Asked Questions

How do I get the most common element from a Counter?

Use most_common(1), which returns a list with one tuple. To get just the element, use most_common(1)[0][0]. If the counter is empty, this will raise an IndexError, so check if counter first.

Can Counter count elements in a numpy array or pandas Series?

Yes, you can pass a flattened numpy array or a pandas Series directly to Counter(). For a 2D numpy array, use Counter(array.flatten()). For a pandas Series, Counter(series) counts the values. This works because both are iterables of hashable elements.

Why does Counter return 0 for missing keys instead of raising an error?

This is a deliberate design choice to simplify counting logic. When you increment a key, you don’t want to check if it exists first. The __missing__ method is overridden to return 0, which is a common pattern in counting dictionaries. If you need a different default, use collections.defaultdict instead.

How do I convert a Counter back to a regular dictionary?

Simply call dict(counter). This produces a plain dictionary with the same key-value pairs. However, note that the resulting dictionary will raise KeyError for missing keys, unlike the Counter.

Is Counter thread-safe for concurrent updates?

No, Counter is not thread-safe. If multiple threads update the same counter simultaneously, you may lose counts due to race conditions. Use a lock (e.g., threading.Lock) or consider using collections.Counter with a multiprocessing.Manager for process-safe counting, though the latter has overhead.

Can I use Counter with non-integer counts?

Technically, you can store any value, but the arithmetic operations assume numeric counts. If you store strings, operations like + will concatenate strings, which is rarely what you want. Stick to integers or floats for meaningful counting.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.