tags:

views:

452

answers:

3

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

+6  A: 
>>> [1, 2, 3, 4, 1, 4, 1].count(1)
3
Łukasz
+3  A: 

list.count(x) returns the number of times x appears in a list

see: http://docs.python.org/tutorial/datastructures.html#more-on-lists

Silfverstrom
A: 

I use if x in [] to test for the existence of values, count is meant for another purpose, and for huge lists it's also faster than count. It returns True or False:

Edit: Sorry, I misunderstood your question, my bad.

>>> lst = [1, 2, 3, 4, 5]
>>> 3 in lst
True
>>> 9 in lst
False
Wez