🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeCounter Python: Count Items in a List

Counting the frequency of each value in a Python list gives you a tally of repeated and one-off items. Python’s collections.Counter builds that tally from an iterable, storing each hashable value with its count.
I’ll show how to build and update a Counter, then explain when list.count() is a better fit.
TL;DR
Use collections.Counter to turn an iterable into a mapping of each hashable value to its frequency.
- Import it with from collections import Counter and pass a list, string or other iterable.
- Use most_common(n) for the top results, and update() to add more observations.
- Use list.count(value) when you need only one value’s frequency.
What Is a Counter in Python?
Counter is a class in Python’s standard-library collections module. It is a dictionary subclass that stores each distinct, hashable element as a key and its frequency as the value.
A frequency is the number of times a value appears. Pass an iterable such as a list or string to count its elements.
For text analysis, decide how to split text into words. A string passed directly to Counter counts characters. This means spaces and punctuation are also counted if they remain in the string.
A mapping constructor can combine a tally produced elsewhere with another batch. If the input is a list of pairs, convert it to a dictionary first when each pair represents an element and its count. Passing pairs directly counts each pair as an item instead, which often surprises readers working with grouped data.
How to Count Items with Counter Step by Step
Import the class, give it the values to count, then inspect the resulting key-count pairs. The same object can answer a missing-value check and return a ranked list.
Step 1: Create a Counter from an iterable
I ran python3 counter_demo.py on a list of six words. It printed Counter({‘red’: 3, ‘blue’: 2, ‘green’: 1}), so repeated values become counts and unique values remain present once as keys.
from collections import Counter
words = "red blue red green blue red".split()
counts = Counter(words)
print(counts)
print(counts.most_common(2))
print(counts["purple"])
try:
Counter([["red"], ["blue"]])
except TypeError as error:
print(type(error).__name__ + ": " + str(error))
items = ["red", "blue", "red", "green"]
print(Counter(items) == {"red": 2, "blue": 1, "green": 1})
print(items.count("red"), Counter(items)["red"])
The output shows the ranked frequencies, a zero for an absent key and the input error below:
Counter({'red': 3, 'blue': 2, 'green': 1})
[('red', 3), ('blue', 2)]
0
TypeError: unhashable type: 'list'
True
2 2

The absent key purple reads as zero. The final line compares list.count() with the tally for one value. Both return two for this input.
Step 2: Read the top counts
most_common(n) returns up to n pairs, ordered from the greatest count to the least. With no argument, it returns all stored entries. In the run above, most_common(2) returned red with three and blue with two.
Equal counts follow encounter order in current Python documentation. For a single statistical mode, Python’s statistics.mode() expresses that question directly. multimode() returns tied modes.
Step 3: Add another batch
Call update() with another iterable to add its frequencies to the existing tally. Passing a mapping adds its values as counts, which differs from counting the mapping’s keys. For example, adding a batch with blue twice and yellow once increases those totals without removing the earlier red and green entries.
Counter Edge Cases and Method Choices
Choose the operation based on the shape of the input and whether you need every frequency or one answer. These differences prevent common type errors and misleading results.
Unary plus creates a Counter containing only positive counts after signed arithmetic. Delete a key when it should no longer appear in membership checks.
I passed nested lists to Counter and got TypeError: unhashable type: ‘list’. Convert each list to a tuple when its values can serve as immutable keys.
| Case | Behavior | What to do |
|---|---|---|
| Unhashable key | Nested list raises TypeError | Use a tuple key when appropriate |
| Zero or negative count | elements() omits it | Use subtract() if signed differences must remain |
| One value lookup | list.count(value) scans the sequence | Use Counter when several frequencies are needed |
For one requested value, items.count(value) scans a list. Counter builds a tally for the full iterable in one pass, which helps when you query several values.
Runtime depends on input size and key behavior, so measure the workload before comparing speed.
most_common() returns a list and does not reorder the Counter object. To create a separately sorted list, sort its items().
For word tallies, normalize capitalization before counting when case should not distinguish entries. Counter treats each supplied token as distinct.
See Text Mining Python for broader text work and Python standard-library modules for related built-ins.
Conclusion
Counter provides a compact way to retain a frequency table for later lookups. Check Python’s Counter documentation for supported methods and arithmetic.
FAQ
These quick answers cover the common counting questions that remain after the examples.
How do I import Counter in Python?
Use from collections import Counter. It is part of Python’s standard-library collections module.
How do I count characters in a string?
Pass the string to Counter, such as Counter(‘banana’). This counts each character, including spaces and punctuation.
How do I sort a Counter by count?
Call most_common() for descending count order, or sort counter.items() for an explicit sorted list of pairs.


