Python generator to yield everything from another generator call

John Zwinck picture John Zwinck · Jun 6, 2011 · Viewed 7.2k times · Source

I have a Python generator that can call itself to get more elements to yield. It looks like this:

def gen(list):
    # ...
    if list:
        for x in gen(list[1:]):
            yield x

My question is about the last two lines: is there a more concise way to express this? I am hoping for something like this (understanding this isn't valid Python as-is):

def gen(list):
    # ...
    if list:
        yield each in gen(list[1:])

Answer

kindall picture kindall · Jun 6, 2011

There's been some call for a yield from or the like that "passes through" all the values returned by a subgenerator. See PEP 380 for some ideas that have been bounced around. However, nothing has been implemented yet. Your first example is correct.