To count the number of times an item appears in a list in Python, you can use the count()
method. The count()
method is a built-in list method that takes an item as an argument and returns the number of occurrences of that item in the list. Here’s an example:
# Input list
my_list = [1, 2, 3, 4, 3, 2, 1, 5, 6, 7, 6, 5]
# Item to count
item = 3
# Get the count of occurrences of the item in the list
item_count = my_list.count(item)
# Print the result
print("Number of occurrences of", item, "in the list:", item_count)
Output:
Number of occurrences of 3 in the list: 2
In this example, the my_list
list is the input list in which we want to count the occurrences of the item
value, which is set to 3. The count()
method is called on my_list
with item
as the argument, which returns the count of occurrences of item
in the list. The resulting count is stored in the variable item_count
, and then printed as the final result.
+ There are no comments
Add yours