Iterators and generators
Generator expressions
Stream values through built-in aggregations.
Lesson 56 of 63
Reading: about 1 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
A generator expression uses parentheses and computes items as its consumer requests them. It is useful when an aggregate can consume one value at a time.
Worked example
sessions = [10, 20, 30]
print(sum(value for value in sessions if value >= 20))
print(any(value > 25 for value in sessions))50 True
Why this works
sum consumes qualifying numbers. any stops as soon as a true condition appears; it need not inspect later values.
Another case
values = (n * 2 for n in range(3))
print(list(values))
print(list(values))[0, 2, 4] []
Practice
What does sum(value for value in sessions if value > 30) return?
Check the practice result
Reveal answer
It returns 0 because no values match and sum of an empty iterable is zero.
Try another case
For sessions = [10, 20, 30], what does any(value > 100 for value in sessions) return?
Check your answer
Reveal answer
False. No value matches, so any() checks every item and returns False.
Your progress
Reveal the check answer or reach the end to complete this lesson.