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 of elements matching particular condition in Python
In this article, we will see how to count elements in a Python list that match a particular condition. We'll explore different approaches to filter and count elements based on specific criteria.
Using Generator Expression with sum()
This approach uses a generator expression with an if condition inside the sum() function. The expression generates 1 for each element that matches the condition ?
Example
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:")
print(days)
# Count elements that are 'Mon' or 'Wed'
count = sum(1 for day in days if day in ('Mon', 'Wed'))
print("Number of times the condition is satisfied:")
print(count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied: 3
Using map() with lambda
Here we use map() with a lambda function to apply the condition to each element. The lambda returns True (1) or False (0), and sum() counts the True values ?
Example
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:")
print(days)
# Count using map and lambda
count = sum(map(lambda day: day in ('Mon', 'Wed'), days))
print("Number of times the condition is satisfied:")
print(count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied: 3
Using reduce()
The reduce() function applies a function cumulatively to all elements in the list. We use it with a lambda function that accumulates the count of matching elements ?
Example
from functools import reduce
days = ['Mon', 'Wed', 'Mon', 'Tue', 'Thu']
# Given list
print("Given list:")
print(days)
# Count using reduce
count = reduce(lambda total, day: total + (day in ('Mon', 'Wed')), days, 0)
print("Number of times the condition is satisfied:")
print(count)
Given list: ['Mon', 'Wed', 'Mon', 'Tue', 'Thu'] Number of times the condition is satisfied: 3
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Generator Expression | High | Excellent | Most cases |
| map() + lambda | Medium | Good | Functional programming |
| reduce() | Low | Fair | Complex accumulation |
Conclusion
The generator expression with sum() is the most readable and efficient approach for counting elements. Use map() for functional programming style, and reduce() for complex accumulation patterns.
