Python Generator Expressions Explained
A Python generator expression produces values on demand using parentheses. It looks like a list comprehension, but does not build the whole result list.
Read List comprehensions and Generators and yield first.
Write a generator expression
Use (expression for item in iterable). Each request computes the next result.
squares = (number * number for number in range(4))
print(next(squares))
print(next(squares))
print(list(squares))
This prints 0, 1, then the remaining squares [4, 9].
Filter values with if
Add an if condition to skip unwanted items. The condition runs as you consume the generator.
scores = [3, 8, 5, 10]
passing = (score for score in scores if score >= 6)
print(list(passing))
print(list(passing))
The first call prints [8, 10]. The generator supplies no items on the second call.
Pass a generator expression to sum()
Functions such as sum() accept iterables. When the generator expression is the only argument, omit its extra parentheses.
prices = [4, 7, 9]
print(sum(price * 2 for price in prices))
This prints 40 without first making a list of doubled prices.
Note: Choose a list when you need indexing or repeated passes. A generator expression is useful for consuming results once. It still keeps access to its input, so an existing input list stays in memory.
See also: Iterators, List comprehensions.
Your turn
Create a generator expression for the squares in numbers, then print their sum.
numbers = [2, 3, 4]
# add two lines: create squares with a generator expression, then print sum(squares)
Expected output
29