How can I count the occurrences of a list item?


Given an item, how can I count its occurrences in a list in Python?

12/20/2018 8:38:50 PM

Accepted Answer

If you only want one item's count, use the count method:

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

Don't use this if you want to count multiple items. Calling count in a loop requires a separate pass over the list for every count call, which can be catastrophic for performance. If you want to count all items, or even just multiple items, use Counter, as explained in the other answers.

11/15/2017 9:48:15 PM

If you are using Python 2.7 or 3 and you want number of occurrences for each element:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow