99. Generators with yield from

Here are 10 Python code snippets demonstrating the use of yield from for delegating part of a generator’s iteration to another generator:


1. Simple Delegation

def generator1():
    yield from [1, 2, 3]

def generator2():
    yield from generator1()
    yield 4

for value in generator2():
    print(value)  # Output: 1, 2, 3, 4

2. Delegating Multiple Iterables

def generator():
    yield from range(3)
    yield from "abc"

for value in generator():
    print(value)  # Output: 0, 1, 2, a, b, c

3. Delegating to Another Generator Function


4. Flattening Nested Lists


5. Combining Results from Multiple Generators


6. Delegating to Built-in Generators


7. Bidirectional Communication


8. Handling Return Values


9. Processing Nested Iterables


10. Generator Pipelines


These examples illustrate how yield from simplifies delegation between generators, making it easier to compose and manage generator logic while maintaining readability.

Last updated