Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Count occurrences of an element in a list in Python
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
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
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
Advertisements
