Counting Occurrences Using Comprehension
suggest changeWhen we want to count the number of items in an iterable, that meet some condition, we can use comprehension to produce an idiomatic syntax:
# Count the numbers in `range(1000)` that are even and contain the digit `9`:
print (sum(
1 for x in range(1000)
if x % 2 == 0 and
'9' in str(x)
))
# Out: 95
The basic concept can be summarized as:
- Iterate over the elements in
range(1000)
. - Concatenate all the needed
if
conditions. - Use 1 as expression to return a 1 for each item that meets the conditions.
- Sum up all the
1
s to determine number of items that meet the conditions.
Note: Here we are not collecting the 1
s in a list (note the absence of square brackets), but we are passing the ones directly to the sum
function that is summing them up. This is called a generator expression, which is similar to a Comprehension.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents