I stumbled across this question when browsing through StackOverflow and it got me thinking: what’s the best way to count the number of elements in a list that match a certain condition? Can you generalize this way to both general conditions (e.g. x>3
) and regular expressions (e.g. 'a.*'
)?
Short answer: you can count the number of elements x
that match a certain condition(x)
by using the one-liner expression sum(condition(x) for x in lst)
. This creates a generator expression that returns True
for each element that satisfies the condition and False
otherwise. Since the True
and False
values are represented by integer 1 and 0 values, you get the number of matching elements by summing over the iterable.
Try it yourself with the interactive code shell:
In case, the browser interpreter doesn’t show up in your browser, here’s the raw Python code:
## FRAMEWORK FOR CONDITIONAL COUNT ## # Define any condition here def condition(x): return x > 10 # Create the list lst = [10, 11, 42, 1, 2, 3] # Count the number of matching elements print(sum(condition(x) for x in lst)) # What's the output?
Related articles:
Python List Count With Condition
How can you count elements under a certain condition in Python? For example, what if you want to count all even values in a list? Or all prime numbers? Or all strings that start with a certain character? There are multiple ways to accomplish this, let’s discuss them one by one.
Say, you have a condition for each element x
. Let’s make it a function with the name condition(x)
. You can define any condition you want—just put it in your function. For example this condition returns True for all elements that are greater than the integer 10:
def condition(x): return x > 10 print(condition(10)) # False print(condition(2)) # False print(condition(11)) # True
But you can also define more complicated conditions such as checking if they are prime numbers.
Python List Count If
How can you count the elements of the list IF the condition is met?
The answer is to use a simple generator expression sum(condition(x) for x in lst)
:
>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3] >>> sum(condition(x) for x in lst) 2
The result indicates that there are two elements that are larger than 10. You used a generator expression that returns an iterator of Booleans. Note that the Boolean True
is represented by the integer value 1 and the Boolean False
is represented by the integer value 0. That’s why you can simply calculate the sum over all Booleans to obtain the number of elements for which the condition holds.
Python List Count Greater / Smaller Than
If you want to determine the number of elements that are greater than or smaller than a specified value, just modify the condition in this example:
>>> def condition(x): return x>10 >>> lst = [10, 11, 42, 1, 2, 3] >>> sum(condition(x) for x in lst) 2
For example, to find the number of elements smaller than 5, use the condition x<5 in the generator expression:
>>> lst = [10, 11, 42, 1, 2, 3] >>> sum(x<5 for x in lst) 3
Python List Count Zero / Non-Zero
To count the number of zeros in a given list, use the list.count(0)
method call.
To count the number of non-zeros in a given list, you should use conditional counting as discussed before:
def condition(x): return x!=0 lst = [10, 11, 42, 1, 2, 0, 0, 0] print(sum(condition(x) for x in lst)) # 5
Python List Count Lambda + Map
An alternative is to use a combination of the map and the lambda function.
Related articles:
- [Full Tutorial] Map Function: manipulates each element in an iterable.
- [Full Tutorial] Lambda Function: creates an anonymous function.
Here’s the code:
>>> sum(map(lambda x: x%2==0, [1, 2, 3, 4, 5])) 2
You count the number of even integers in the list.
- The lambda function returns a truth value for a given element
x
. - The map function transforms each list element into a Boolean value (1 or 0).
- The sum function sums up the “1”s.
The result is the number of elements for which the condition evaluates to True
.
Python List Count Regex / Count Matches
Given a list of strings. How can you check how many list elements match a certain regex pattern? (If you need a refresher on Python regular expressions, check out my ultimate guide on this blog – it’s really ultimate!)
- List
lst
of string elements - Pattern
p
to be matched against the strings in the list.
Solution: Use the concept of generator expressions with the ternary operator.
Related articles:
Here’s the code:
>>> import re >>> p = 'a...e' >>> lst = ['annie', 'alice', 'apex'] >>> sum(1 if re.match(p, x) else 0 for x in lst) 2
Python List Count Wildcard
Do you want to count all string occurrences of a given prefix (e.g. prefix "Sus"
for strings "Susie"
, "Susy"
, "Susi"
)?
Solution: Again you can use the concept of generator expressions with the ternary operator.
Related articles:
Here’s the code for this one using the wildcard operator in a pattern to count all occurrences of this pattern in the list.
>>> import re >>> lst = ['Susi', 'Ann', 'Susanne', 'Susy'] >>> pattern = 'Sus.*' >>> frequency = sum(1 if re.match(pattern, x) else 0 for x in lst) >>> print(frequency) 3
The generator expression produces a bunch of 1s and 0s—the former if the list element starts with prefix 'Sus'
and the latter if it doesn’t. By summing over all elements, you get the number of matches of the wildcard operator.
Where to Go From Here?
You’ve learned how you can get the number of elements that match a certain condition. It can be a Boolean condition or even a regular expression—the framework stays the same.
Do you want to accelerate your learning efficiency? Do you want to work from the comfort of your own home? Do you want to make a comfortable living by coding 3-5 hours for clients online?
Then join my Python freelancer program and take your first steps towards six figures and attainment of your practical code projects in no time!
Are you still unsure? Watch the free software dev online webinar first. It’s fun and you don’t have to have any preknowledge! ?