Python Counting the List Items



The count() method in list class returns the number of times a given object occurs in the list.

Syntax

list.count(obj)

Return Value

Number of occurrence of the object. The count() method returns an integer.

Example 1

The following example demonstrates how you can use the count() method −

lst = [10, 20, 45, 10, 30, 10, 55]
print ("lst:", lst)
c = lst.count(10)
print ("count of 10:", c)

It will produce the following output

lst: [10, 20, 45, 10, 30, 10, 55]
count of 10: 3

Example 2

Even if the items in a list contain expressions, they will be evaluated to obtain the count.

lst = [10, 20/80, 0.25, 10/40, 30, 10, 55]
print ("lst:", lst)
c = lst.count(0.25)
print ("count of 10:", c)

It will produce the following output

lst: [10, 0.25, 0.25, 0.25, 30, 10, 55]
count of 10: 3
python_list_methods.htm
Advertisements