generator next function python code example
Example 1: python generator
# A generator-function is defined like a normal function,
# but whenever it needs to generate a value,
# it does so with the yield keyword rather than return.
# If the body of a def contains yield,
# the function automatically becomes a generator function.
# Python 3 example
def grepper_gen():
yield "add"
yield "grepper"
yield "answer"
grepper = grepper_gen()
next(grepper)
> add
next(grepper)
> grepper
next(grepper)
> answer
Example 2: generator expressions python
>>> genexpr = ('Hello' for i in range(3))
>>> list(genexpr)
['Hello', 'Hello', 'Hello']