Write a Python program to count the number of occurrences of a given element in a given list.
def count_occurrences(lst, element_to_count):
count = 0
for item in lst:
if item == element_to_count:
count += 1
return count
my_list = [1, 2, 3, 4, 2, 2, 5, 2, 6]
element = 2
result = count_occurrences(my_list, element)
print(f"The element {element} appears {result} times in the list.")
Output :
The element 2 appears 4 times in the list.
In this program, we define a function count_occurrences
that takes two arguments: lst
(the list in which we want to count occurrences) and element_to_count
(the element we want to count). We initialize a count
variable to 0 and then iterate through the list, incrementing the count
each time we find an element that matches the one we're counting. Finally, the function returns the count.
If you are a beginner and want to know more about Python programming, you can read my Basics of Python blogs (From part 1 to part 15).
HAPPY LEARNING !!!