Count occurrences of an element in a list in Python

PythonServer Side ProgrammingProgramming

In this article we are given a list and a string. We are required to find how many times the given string is present as an element in the list.

With Counter

The counter function from collections module will give us the count of each element present in the list. From the counting result we can extract only that account fair the index matches with the value of the element we are searching for.

Example

 Live Demo

from collections import Counter
Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Counter(Alist)
print("Number of times the element is present in list:\n",cnt[elem])

Output

Running the above code gives us the following result −

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Given element:
Mon
Number of times the element is present in list:
2

With count

The count function takes in in the given stream as a parameter and searches for that stream in the given list.

Example

 Live Demo

Alist = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
elem = 'Mon'
# Given list and element
print("Given list:\n", Alist)
print("Given element:\n",elem)
cnt = Alist.count('Mon')
print("Number of times the element is present in list:\n",cnt)

Output

Running the above code gives us the following result −

Given list:
['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Given element:
Mon
Number of times the element is present in list:
2
raja
Published on 04-Jun-2020 11:28:53
Advertisements