Hit enter after type your search item

The List Count Function in Python

The Python count() function is used to return the occurrence of the given object in the specified list. For example, we have the following list:

a_list = [“p”,”y”,”t”,”h”,”o”,”n”,”p”,”y”,”p”,]

if we require knowing how many times item “p” occurred in that list then we may use the count() function as follows:


Syntax for using the count function

Following is the general syntax of using the count Python function:


See the following examples for using the count function.

A simple example of counting the occurrence of an object

For the example, I have used the same list as in introduction section. The program will return the number of times “p” and “y” objects occur in the list. Have a look at the code and output:

The Output

What if you require counting of each element in a list?

For getting the count of each element of the list, you may use the Counter subclass. See an example below where a list is created and the occurrence of each list element is returned:

The output of above code is:

Counter({‘Python’: 3, ‘CSS’: 2, ‘HTML’: 2, ‘C-Sharp’: 1, ‘Java’: 1, ‘JavaScript’: 1})

For learning more about using the Counter subclass, you may visit this tutorial: Python Counter subclass.

Getting the total count of a list

If you need to get the total number of elements in a list then use the len() function. The len function takes an argument that can be a list or other sequences like tuple, dict etc.

As of our topic, for getting the total count of a list, the example below shows how you can do that:

See online demo and code

The output:

Python list count

You can see, the len() returned the total count of elements in the list. For more on len(), visit its tutorial: the len() function.

This div height required for enabling the sticky sidebar