Write a Python Program to Count the Occurrence of an Item in a List

In Python, you can easily count the occurrence of an item in a list using the count() method.

This method returns the number of times a given element appears in the list.


Here’s a Python program that demonstrates how to use the count() method to count the occurrence of an item in a list:

my_list = [1, 2, 3, 4, 5, 2, 3, 2, 1]

# Count the number of times 2 appears in the list
count = my_list.count(2)

# Print the result
print("The number of times 2 appears in the list is:", count)

Output:

The number of times 2 appears in the list is: 3

In this program, we first define a list called my_list.

We then use the count() method to count the number of times the integer 2 appears in the list.

Finally, we print the result using the print() function.

You can also use the count() method with other data types, such as strings.

Here’s an example:

my_list = ['apple', 'banana', 'orange', 'banana', 'apple', 'grape']

# Count the number of times 'apple' appears in the list
count = my_list.count('apple')

# Print the result
print("The number of times 'apple' appears in the list is:", count)

Output:

The number of times 'apple' appears in the list is: 2

In this example, we define a list called my_list that contains strings instead of integers.

We use the count() method to count the number of times the string ‘apple’ appears in the list.

Finally, we print the result using the print() function.


In conclusion, counting the occurrence of an item in a list is very simple in Python.

You just need to use the count() method, which returns the number of times a given element appears in the list.