To count the number of occurrences of a specific element in a list in Python, you can use the count()
method.
In this example,
my_list
with elements.count()
method of the list my_list
to count the occurrences of a specific element.count()
method returns the number of times the element appears in the list.my_list = [1, 2, 3, 1, 4, 1, 5]
count = my_list.count(1)
print("Count of 1 in the list is:", count)
Count of 1 in the list is: 3
In this example,
str_list
with string elements.count()
method of the list str_list
to count the occurrences of a specific string.count()
method returns the number of times the string appears in the list.str_list = ["apple", "banana", "apple", "cherry", "apple"]
count = str_list.count("apple")
print("Count of 'apple' in the list is:", count)
Count of 'apple' in the list is: 3
In this tutorial, we learned How to count the Number of Occurrences of Specific Element in the List in Python language with well detailed examples.