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.
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.
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])
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
The count function takes in in the given stream as a parameter and searches for that stream in the given list.
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)
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