How to Count Frequency Using Counter in Python
Use
Counter from Python's collections module to count the frequency of items in a list or string. Simply pass your data to Counter(), and it returns a dictionary-like object with items as keys and their counts as values.Syntax
The basic syntax to use Counter is:
from collections import Counter- imports the Counter class.Counter(iterable)- creates a Counter object counting elements in the iterable (like a list or string).- The result is a dictionary-like object where keys are items and values are their counts.
python
from collections import Counter counter = Counter(iterable)
Example
This example shows how to count the frequency of letters in a string and numbers in a list using Counter.
python
from collections import Counter # Count frequency of letters in a string text = 'hello world' letter_counts = Counter(text) print('Letter counts:', letter_counts) # Count frequency of numbers in a list numbers = [1, 2, 2, 3, 3, 3, 4] number_counts = Counter(numbers) print('Number counts:', number_counts)
Output
Letter counts: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
Number counts: Counter({3: 3, 2: 2, 1: 1, 4: 1})
Common Pitfalls
Common mistakes when using Counter include:
- Passing a non-iterable object, which causes an error.
- Expecting
Counterto sort results automatically; it does not sort by count. - Modifying the
Counterobject incorrectly instead of using its methods.
Always ensure your input is iterable and use most_common() to get sorted counts.
python
from collections import Counter # Wrong: passing an integer (not iterable) # counter = Counter(123) # This raises TypeError # Right: pass a string or list counter = Counter('123') print(counter) # To get sorted counts by frequency counter = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'apple']) print(counter.most_common())
Output
Counter({'1': 1, '2': 1, '3': 1})
[('apple', 3), ('banana', 2), ('orange', 1)]
Quick Reference
Here is a quick summary of useful Counter methods:
| Method | Description |
|---|---|
| Counter(iterable) | Create a Counter object counting elements in iterable |
| most_common(n) | Return a list of the n most common elements and their counts |
| elements() | Return an iterator over elements repeating each as many times as its count |
| update(iterable) | Add counts from another iterable or mapping |
| subtract(iterable) | Subtract counts using another iterable or mapping |
Key Takeaways
Use collections.Counter to count frequency of items in any iterable easily.
Pass a list, string, or other iterable to Counter to get counts as a dictionary-like object.
Use most_common() to get items sorted by frequency.
Ensure input is iterable to avoid errors.
Counter provides helpful methods to update, subtract, and iterate over counts.