Python List count() Method

The count() method in Python is a built-in function used to count the number of occurrences of a specified item in a list. The method returns an integer representing the number of times the item appears in the list.

Syntax

list.count(item)

Parameters

  • item: The item to be counted in the list.

Examples

Example 1: Counting Occurrences of an Element in a List

Let’s consider a list and try to count the occurrences of an element in the list using the count() method:

a = ["dog", "cat", "horse", "bird", "dog"]
print(a.count("dog"))

In this example, we have created a list a containing five elements, with two occurrences of the element “dog”. We have used the count() method to count the occurrences of the element “dog” in the list. The method returns the number of times the item appears in the list. Finally, we have printed the result, which will be 2.

Example 2: Counting Occurrences of an Element that Does Not Exist

If the item is not found in the list, the count() method returns 0:

a = ["dog", "cat", "horse", "bird"]
print(a.count("monkey"))

In this example, we have created a list a containing four elements. We have used the count() method to count the occurrences of the element “monkey” in the list. Since the element does not exist in the list, the method returns 0. Finally, we have printed the result, which will be 0.

Example 3: Counting Occurrences of Elements in a List of Integers

The count() method can also be used to count the occurrences of elements in a list of integers:

a = [1, 2, 3, 4, 5, 2, 3, 4, 5]
print(a.count(2))
print(a.count(3))

In this example, we have created a list a containing nine elements, with two occurrences of the elements 2 and 3. We have used the count() method to count the occurrences of the elements 2 and 3 in the list. The method returns the number of times the items appear in the list. Finally, we have printed the results, which will be 2 and 2, respectively.

In conclusion, the count() method in Python is a useful built-in function for counting the occurrences of elements in a list. It is simple to use and can be applied to lists of various data types.

Leave a Reply

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