In this article, we will discuss about the usage details of count()
method of List in Python.
Table Of Contents
Introduction
The count()
method of list accepts an element
as an argument, and returns the occurrence count of that element
in the list. Basically it checks how many times the given element
appears in the list
and return that number.
Syntax of List count() method
occurrenceCount = list.count(element)
Parameters
element
: The element whose occurrence count need to be fetched from the list.
Returns
It returns occurrence count of the given element in the list. Basically how many times the given element appears in the list. If given element does not exist in the list then it will return zero.
Let us see some examples.
Example 1 of List count() method
Suppose we have a list of numbers and we want to know how many times number 11
appears in this list. For that we will call the count() method of list and pass number 11 as argument in it. The count() method will return a number i.e. how many times number 11 appears in the list. Let us see the example,
listOfNumbers = [11, 22, 33, 11, 44, 11, 55] element = 11 # Get occurrence count of given element in list occurrenceCount = listOfNumbers.count(element) print(occurrenceCount)
Output:
Latest Python - Video Tutorial
3
It returned 3, because the number 11 occurred at 3 different places in the list.
Example 2 of List count() method
Suppose we have a list of strings and now we want to know the occurrence count of a string “why” in the list. For that, again we will call the count() function of the list in past the string “why” in it.
listOfStrings = ["is", "at", "what", "how", "the"] element = "why" # Get occurrence count of given element in list occurrenceCount = listOfStrings.count(element) print(occurrenceCount)
Output:
0
As the list does not have any string “why” in it, therefore the count() method returns zero in this case.
Example 3 of List count() method
Let’s see another example in which we will try to find the occurrence count of string “how”.
listOfStrings = ["is", "how", "what", "how", "the", "how", "how"] element = "how" # Get occurrence count of given element in list occurrenceCount = listOfStrings.count(element) print(occurrenceCount)
Output:
4
The string “how” occurred at 4 different places in the list, therefore the count method returned the number 4.
Summary
In this article we learn all about the count() method of list in Python.
Latest Video Tutorials