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
-
Economics & Finance
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. Python provides several methods to count occurrences, each with different advantages.
Using count() Method
The count() method is the most straightforward approach. It takes the element as a parameter and returns the number of times it appears in the list ?
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
element = 'Mon'
# Given list and element
print("Given list:", days)
print("Given element:", element)
count = days.count(element)
print("Number of times the element is present in list:", count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Given element: Mon Number of times the element is present in list: 2
Using Counter from collections
The Counter function from the collections module counts all elements in the list and returns a dictionary-like object. This is useful when you need counts of multiple elements ?
from collections import Counter
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
element = 'Mon'
# Given list and element
print("Given list:", days)
print("Given element:", element)
counter = Counter(days)
print("Number of times the element is present in list:", counter[element])
print("All counts:", dict(counter))
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Given element: Mon
Number of times the element is present in list: 2
All counts: {'Mon': 2, 'Wed': 1, 'Tue': 1, 'Thu': 1}
Using List Comprehension
You can also count occurrences using list comprehension with sum() ?
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
element = 'Mon'
count = sum(1 for day in days if day == element)
print("Number of times the element is present in list:", count)
Number of times the element is present in list: 2
Comparison
| Method | Best For | Time Complexity |
|---|---|---|
count() |
Single element counting | O(n) |
Counter() |
Multiple element counting | O(n) |
| List comprehension | Custom conditions | O(n) |
Conclusion
Use list.count() for simple counting of a single element. Use Counter() when you need counts of multiple elements. List comprehension is useful for complex counting conditions.
