Python counts the number of list items

Counting List Items in Python

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

Syntax

list.count(obj)

Return Value

The number of times an object appears. The count() method returns an integer.

Example 1

The following example demonstrates how to 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 the 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)

This will produce the following output: −

lst: [10, 0.25, 0.25, 0.25, 30, 10, 55]
count of 10: 3

Leave a Reply

Your email address will not be published. Required fields are marked *