Iteration
Generator Expressions
A list comprehension is eager: it builds a list immediately. That is useful when you need to store or reuse the results.
Source
numbers = [1, 2, 3, 4]
list_squares = [number * number for number in numbers]
print(list_squares)Output
[1, 4, 9, 16]A generator expression is lazy: it creates an iterator that produces values as they are consumed. After two next() calls, only the remaining squares are left.
Source
stream_squares = (number * number for number in numbers)
print(next(stream_squares))
print(next(stream_squares))
print(list(stream_squares))Output
1
4
[9, 16]Generator expressions are common inside reducing functions. When a generator expression is the only argument, the extra parentheses can be omitted.
Source
print(sum(number * number for number in numbers))Output
30Notes
- List, dict, and set comprehensions build concrete collections.
- Generator expressions produce one-pass iterators.
- Use generator expressions when the consumer can process values one at a time.
See also
- prerequisite: Comprehensions
- related: Generators
- related: Itertools
- related: Yield From
Run the complete example
Expected output
[1, 4, 9, 16]
1
4
[9, 16]
30
Execution time appears here after you run the example.