SyntaxStudy
Sign Up
Python Intermediate 4 min read

yield from

yield from

yield from delegates to a sub-generator, forwarding all values. It simplifies generator chaining and is required for proper coroutine delegation.

Example
def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

print(list(flatten([1, [2, [3, 4]], 5])))
# [1, 2, 3, 4, 5]
Pro Tip

yield from also forwards send() and throw() calls to the sub-generator.