0
0
PythonHow-ToBeginner · 3 min read

How to Use Counter in Python: Simple Guide with Examples

Use Counter from Python's collections module to count occurrences of items in a list, string, or any iterable. Import it with from collections import Counter, then create a counter object by passing your data, like Counter(['a', 'b', 'a']).
📐

Syntax

The Counter class is imported from the collections module. You create a counter by passing an iterable (like a list or string) to Counter(). It returns a dictionary-like object where keys are items and values are their counts.

Example parts:

  • from collections import Counter: imports the Counter class.
  • Counter(iterable): creates a counter object counting each item in the iterable.
python
from collections import Counter

counter = Counter(['apple', 'banana', 'apple', 'orange'])
💻

Example

This example shows how to count letters in a string and print the counts.

python
from collections import Counter

text = 'hello world'
counter = Counter(text)
print(counter)
Output
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
⚠️

Common Pitfalls

One common mistake is trying to use Counter without importing it first. Another is passing a non-iterable object, which causes an error. Also, remember that Counter counts items exactly as they appear, so case differences matter ('a' and 'A' are different).

python
from collections import Counter

# Wrong: no import
# counter = Counter(['a', 'b', 'a'])  # NameError

# Wrong: passing non-iterable
# counter = Counter(123)  # TypeError

# Right usage
counter = Counter(['a', 'b', 'a'])
print(counter)
Output
Counter({'a': 2, 'b': 1})
📊

Quick Reference

MethodDescription
Counter(iterable)Create a counter from items in iterable
counter.most_common(n)Return list of n most common items and counts
counter.elements()Return iterator over elements repeating each as many times as its count
counter.update(iterable)Add counts from another iterable or mapping
counter.subtract(iterable)Subtract counts using another iterable or mapping

Key Takeaways

Import Counter from collections to count items easily in Python.
Pass an iterable like a list or string to Counter to get counts of each item.
Counter returns a dictionary-like object with items as keys and counts as values.
Common errors include forgetting to import or passing non-iterables.
Use methods like most_common() to get the most frequent items quickly.