Search code examples
pythonpython-3.xgeneratoryield

How two consecutive yield statement work in python?


I stumble upon this code from pymotw.com in merging and splitting section.

from itertools import *


def make_iterables_to_chain():
    yield [1, 2, 3]
    yield ['a', 'b', 'c']


for i in chain.from_iterable(make_iterables_to_chain()):
    print(i, end=' ')
print()

I can not understand how make_iterables_to_chain() is working. It contains two yield statement, how does it work? I know how generators work but there but there was only single yield statement.

Help, please!


Solution

  • The same way a single yield works.

    You can have as many yields as you like in a generator, when __next__ is called on it, it will execute until it bumps into the next yield. You then get back the yielded expression and the generator pauses until it's __next__ method is invoked again.

    Run a couple of next calls on the generator to see this:

    >>> g = make_iterables_to_chain()  # get generator
    >>> next(g) # start generator, go to first yield, get result
    [1, 2, 3]
    >>> next(g) # resume generator, go to second yield, get result
    ['a', 'b', 'c']
    >>> # next(g) raises Exception since no more yields are found