Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the occurrences of a list item?

Tags:

python

list

count

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

like image 755
weakish Avatar asked Apr 08 '10 13:04

weakish


1 Answers

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

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

Important Note regarding count performance

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.

like image 192
Łukasz Avatar answered Oct 01 '22 09:10

Łukasz