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 the sublists containing given element in a list in Python
When working with lists in Python, you often need to count how many times a specific element appears. This article demonstrates three different approaches to count occurrences of a given element in a list.
Using range() and len()
This method uses a loop with range() and len() to iterate through the list indices. A counter variable tracks how many times the element is found ?
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
target = 'Mon'
print("Given list:", days)
print("Element to check:", target)
count = 0
for i in range(len(days)):
if target == days[i]:
count += 1
print("Number of times the element appears:", count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Element to check: Mon Number of times the element appears: 2
Using sum() with Generator Expression
This approach uses sum() with a generator expression to count matches. Each True value from the comparison is treated as 1 ?
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
target = 'Mon'
print("Given list:", days)
print("Element to check:", target)
count = sum(target == item for item in days)
print("Number of times the element appears:", count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Element to check: Mon Number of times the element appears: 2
Using the count() Method
Python's built-in count() method provides the most direct way to count occurrences of an element ?
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
target = 'Mon'
print("Given list:", days)
print("Element to check:", target)
count = days.count(target)
print("Number of times the element appears:", count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Element to check: Mon Number of times the element appears: 2
Using Counter from collections
For more complex counting operations, Counter can count all elements at once ?
from collections import Counter
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
target = 'Mon'
print("Given list:", days)
print("Element to check:", target)
counter = Counter(days)
count = counter[target]
print("Number of times the element appears:", count)
print("All element counts:", dict(counter))
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
Element to check: Mon
Number of times the element appears: 2
All element counts: {'Mon': 2, 'Wed': 1, 'Tue': 1, 'Thu': 1}
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
range()/len() |
Low | Slow | Learning purposes |
sum() |
Medium | Medium | Complex conditions |
count() |
High | Fast | Simple counting |
Counter |
High | Fast | Multiple elements |
Conclusion
Use list.count() for simple element counting as it's the most readable and efficient. Use Counter when you need to count multiple elements simultaneously.
