Count occurrences in a Python list
Use list.count for one target or Counter for a frequency table, and handle unhashable elements and empty-input percentages deliberately.
Use items.count(value) to count one target. When you need counts for many values, build a collections.Counter once.
Count a single value
items = ["a", "b", "a", "c", "a"]
print(items.count("a")) # 3
count() scans the list using equality comparisons. It also works with unhashable elements such as lists.
Build a frequency table
from collections import Counter
counts = Counter(items)
print(counts["a"]) # 3
print(counts["missing"]) # 0
print(counts.most_common(2)) # [('a', 3), ('b', 1)]
Counter is a dictionary subclass whose elements must be hashable. For equal counts, most_common() preserves first-encountered order. Reading a missing count yields zero; it does not by itself insert that key.
Count status codes or find duplicates
codes = [200, 200, 404, 500, 200, 404]
print(Counter(codes)) # Counter({200: 3, 404: 2, 500: 1})
duplicates = [value for value, count in counts.items() if count > 1]
print(duplicates) # ['a']
One count() call is linear in list length. Building a Counter is expected linear time for ordinary hashable values, with expected constant-time count lookups. Repeatedly scanning a list for every distinct value can approach quadratic work. Hashing and equality costs still depend on the objects involved.
FAQ
Can Counter count nested lists? Not directly. Converting each inner list to a tuple works only if everything inside that tuple is hashable and the conversion preserves the equality meaning you need. A tuple containing another list is still unhashable.
Can I add or subtract counters? Counter(a) + Counter(b) combines counts; Counter(a) - Counter(b) keeps positive differences. The mutating subtract() method can retain zero and negative counts, so it is not identical to the subtraction operator.
How do I calculate percentages? Divide by the total count and handle empty input explicitly:
items = ["a", "b", "a"]
counts = Counter(items)
percentages = (
{value: 100 * count / len(items) for value, count in counts.items()}
if items else {}
)
print(percentages)
Equality also affects grouping: values such as True and 1 compare equal and share a count as dictionary keys. Normalize or distinguish types first if your domain treats them as different categories.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan