Iteration

Generator Expressions

Generator expressions use comprehension-like syntax to stream values lazily.

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]
SOURCE[a,b,c]FILTERx>0MAPx*2next()
A generator expression composes filter and map lazily; values flow only when next() pulls them.

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

30

Notes

See also

Run the complete example

Example code

Expected output

[1, 4, 9, 16]
1
4
[9, 16]
30

Execution time appears here after you run the example.