Count the Occurrence of an Item in a List in Python

  • Post category:List

Counting the occurrence of an item in a list can be achieved using the count() method. Here are two examples:

Example 1:

my_list = [1, 2, 3, 4, 2, 2, 5, 2]
target = 2
count = my_list.count(target)
print(f"The item {target} appears {count} times in the list.")

Output:

The item 2 appears 4 times in the list.

Example 2:

my_list = ['apple', 'banana', 'apple', 'kiwi', 'apple']
target = 'apple'
count = my_list.count(target)
print(f"The item {target} appears {count} times in the list.")

Output:

The item apple appears 3 times in the list.