When 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:
range(1000)
.if
conditions.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.