List count() Method in Python

Python List count() Method

In Python, the count() method is used to count the occurrences of a specified element in a list. It is a built-in method available for lists in Python.

Here's the basic syntax of the count() method:

count = list_name.count(element)
  • count: This is the variable that will store the number of occurrences of the specified element in the list.
  • list_name: This is the name of the list in which you want to count the occurrences.
  • element: This is the value for which you want to find the count in the list.

Let's see an example of using the count() method:

Example:

# Create a list with some elements
numbers = [1, 2, 3, 4, 2, 5, 2]

# Count the occurrences of the number 2 in the list
count_of_twos = numbers.count(2)

print("Count of 2:", count_of_twos)  # Output: Count of 2: 3

 

As you can see in the example, the count() method returns the number of times the specified element (in this case, the number 2) appears in the list (numbers). In the given list, the value 2 occurs three times, so the count_of_twos variable stores the value 3.