Given an item, how can I count its occurrences in a list in Python?
If you only want one item's count, use the count
method:
>>> [1, 2, 3, 4, 1, 4, 1].count(1) 3
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With