In Python, the list count() method is used to return the number of times an element appears in the list. If the element is not present in the list, it returns 0.
The following is the syntax of the list count() method:
Let's see some examples of the count() method to understand it's working.
In this example, we will understand the use of the count() method to find the total occurrence of an element in the given list.
Output:
Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon'] Count of 'banana' = 3
Explanation:
In this example, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. Since element 'banana' is occurred 3 times in the list, the count() method returned 3.
If the passed value is not present in the list, the count() method returns 0.
Here is an example:
Output:
Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon'] Count of 'kiwi' = 0
Explanation:
In this example, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. Since element 'kiwi' is not a part of the list, the count() method returned 0.
The count() method can be used to check if any duplicate elements are present in the list. Here is an example:
Output:
Given List: ['apple', 'banana', 'banana', 'mango', 'orange', 'banana', 'melon'] The value 'banana' is duplicate. Count of 'banana' = 3
Explanation:
Here, we are given a list consisting of some elements. We used the count() method to count the occurrence of a specific element in the list. We then checked if the returned number is higher or equal to 2 for duplicate elements.
Since, the banana is present in the list for 3 times, the message "The value 'banana' is duplicate" is printed.
We request you to subscribe our newsletter for upcoming updates.