Python Program to Count the Occurrence of an Item in a List
Counting is the process of determining the number of objects or items in a collection. It involves assigning a numerical value to a quantity or a set of objects, which can then be used for various purposes, such as calculations, comparisons, or analysis
Python Code :
The Below Python program that counts the number of times a specified item occurs in a list:
# Define the list and the item to count my_list = [1, 2, 3, 4, 5, 2, 2, 3] item_to_count = 2 # Use the count() method to count the number of occurrences of the item count = my_list.count(item_to_count) # Print the count print("The item", item_to_count, "appears", count, "times in the list.")
In this program, we first define the list that we want to count the occurrences in by assigning it to the variable my_list. We also define the item that we want to count by assigning it to the variable item_to_count.
We then use the count() method of the list to count the number of occurrences of the item in the list. The count() method returns an integer indicating how many times the item appears in the list.
Finally, we print a message that indicates how many times the item appears in the list.
You can replace the my_list and item_to_count variables with any other list and item to count. Note that the count() method only counts exact matches, so if the item appears in the list as a different type (e.g. as a string instead of an integer), it will not be counted.