Lists and Records
Count Matching
Count how many values in a list satisfy a condition — here, readings above a threshold. Incrementing a counter inside a conditional is the simplest aggregate pattern after sum and mean.
By hand
The Pythonic way
sum(1 for v in values if v > threshold) is a generator expression that
produces 1 for each qualifying element; sum adds them up. No explicit
loop or counter variable is needed.
naive.py
values = [4, 7, 2, 9, 1, 8, 3, 6]
threshold = 5
count = 0
for v in values:
if v > threshold:
count = count + 1
print('RESULT:', count)
library.py
values = [4, 7, 2, 9, 1, 8, 3, 6]
threshold = 5
count = sum(1 for v in values if v > threshold)
print('RESULT:', count)
RESULT: 4
Implementation notes
- Every
if v > threshold:event is zero-delta (condition evaluation changes no variables). Matching values are distinguished by thecount = count + 1event that immediately follows; non-matching values jump straight to the next for-header. - The generator expression inside
sum(...)runs in its own scope, so its loop variable does not appear in the trace.