Python Generator Expressions
A generator expression is a comprehension in round brackets that streams values. It builds no list.
A comprehension that streams
Round brackets make a generator expression. The sum() call pulls values through it one by one.
squares = (number * number for number in range(1, 5))
print(sum(squares))List first, or stream it
The list version keeps all four squares. The max() call needs only the largest, so it streams.
squares_list = [number * number for number in range(1, 5)]
print(squares_list)
print(max((number * number for number in range(1, 5))))Answer a yes-or-no question
The any() call stops at the first True it meets. It never needs a list of every answer.
scores = [72, 95, 60]
print(any(score >= 90 for score in scores))Spent after one walk
The first sum() drains the stream. The same expression has nothing left to give.
numbers = (number for number in [1, 2, 3])
print(sum(numbers))
print(sum(numbers))
print(list(numbers))Example
count = sum(1 for number in range(1_000_000))
total = sum(number for number in range(1_000_000))
print("Count:", count)
print("Total:", total)Key points
- Generator expression: a comprehension in round brackets that streams values
- Use a generator expression when you need a total, a best value, or a yes-or-no answer
- Use sum, max, min, any, or all to consume a stream directly
- A list comprehension builds and keeps every value in memory
In this example, the first generator expression yields a 1 for every number in the range. The sum() call counts a million numbers without storing them. The second line builds a fresh stream of the same numbers. Its sum() call adds them as they flow past. No list of a million numbers ever exists in this program. The printed count and total are the same on every run.
Note
A generator expression is spent after one full walk.
A second walk over the same one finds nothing left.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does a second sum() over the same generator expression return?