Python Program - Count the Occurrence of an Item in a List
Here's a Python program that counts the occurrence of an item in a list:
refer to:theitroad.comdef count_occurrences(lst, item): count = 0 for i in lst: if i == item: count += 1 return count # Example usage my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2, 2, 3, 3, 3] print(count_occurrences(my_list, 3)) # Output: 4
In this program, the count_occurrences()
function takes two arguments - lst
(the list to be searched) and item
(the item whose occurrence needs to be counted).
The function initializes a counter variable count
to 0, and then loops through each element of the list lst
. If an element in the list matches the item
, then the count
variable is incremented by 1.
After the loop finishes, the function returns the final value of count
, which represents the number of times the item
appears in the lst
.
In the example usage, we define a list my_list
and call the count_occurrences()
function with arguments my_list
and 3
. The program outputs the number of times 3
appears in my_list
, which is 4
.