Sobes.tech
Junior — Middle

Is it possible in Python to define multiple yield statements within a single generator?

sobes.tech AI

Answer from AI

Yes, in Python, you can use multiple yield statements within a single generator. This allows the generator to yield values at different points in the function, which is convenient for complex logic.

Example:

def multi_yield():
    yield 1
    yield 2
    for i in range(3):
        yield i + 3
    yield 6

for value in multi_yield():
    print(value)

Output will be:

1
2
3
4
5
6

Thus, multiple yield statements in one generator are a normal practice and a powerful tool for creating iterators with different logic.