How do I count the occurrences of a list item?

If you only want a single item’s count, use the count method:

>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3

Important: this is very slow if you are counting multiple different items

Each count call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks, which can be catastrophic for performance.

If you want to count multiple items, use Counter, which only does n total checks.

Leave a Comment