1# A generator-function is defined like a normal function,
2# but whenever it needs to generate a value,
3# it does so with the yield keyword rather than return.
4# If the body of a def contains yield,
5# the function automatically becomes a generator function.
6# Python 3 example
7def grepper_gen():
8 yield "add"
9 yield "grepper"
10 yield "answer"
11grepper = grepper_gen()
12next(grepper)
13> add
14next(grepper)
15> grepper
16next(grepper)
17> answer
1# Size of generators is a huge advantage compared to list
2import sys
3
4n= 80000
5
6# List
7a=[n**2 for n in range(n)]
8
9# Generator
10# Be aware of the syntax to create generators, lika a list comprehension but with round brakets
11b=(n**2 for n in range(n))
12
13print(f"List: {sys.getsizeof(a)} bits\nGenerator: {sys.getsizeof(b)} bits")
1def count_to_ten_generator():
2 for number in range(10):
3 yield number
4my_generator = count_to_ten_generator()
5first_number = next(my_generator)
6list_or_the_rest = list(my_generator)