30. Generator functions

Avoid generating large number of values or objects as they may take up memory. Use yield inside a function to generate values or objects as needed. Functions generating collections using yield are more space efficient and faster.

30.1. Don’t do this

1def generate_sequential_numbers(n):
2    nums = []
3    for i in range(n):
4        nums.append(i)
5    return nums
6
7sum(generate_sequential_numbers(10000000))

30.2. Do this

1def generate_sequential_numbers(n):
2    for i in range(n):
3        yield i
4
5sum(generate_sequential_numbers(10000000))
1generate_sequential_numbers = lambda n: (i for i in range(n))
2
3sum(generate_sequential_numbers(10000000))