Python count() function is used to return the occurrence of the given object in the specified list.
For example, we have the following list:
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 Python count 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 the 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:
#An Demo of count function a_list = ["p","y","t","h","o","n","p","y","p"] print("Total count of 'p' = " ,a_list.count("p")) print("Total count of 'y' = " ,a_list.count("y"))
The Output
Total count of ‘p’ = 3
Total count of ‘y’ = 2
>>>
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:
#An Demo of count function from collections import Counter pro_list = ['Python', 'HTML', 'JavaScript', 'Java', 'Python', 'HTML', 'CSS', 'Python', 'CSS', 'C-Sharp'] print(Counter(pro_list))
The output of above code is:
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:
#An Demo of list count a_list = ["a","z","b","y","f","g","s",10,"t",15,"y","z"] print("Total Number of elements in the list:" , len(a_list))
The output:
You can see, the len() returned the total count of elements in the list. For more on len(), visit its tutorial: the len() function.