Forward generator to caller

def my_range(start, stop, step):
    for i in range(start, stop, step=step):
        yield i

How can I rewrite the above code so I don’t have to (explicitly at least) loop through the inner generator yielding each item one-by-one?

>Solution :

You can simply use the yield from statement to delegate the generator functionality to another generator. In this case, it would be the built-in range() function. Here’s the modified code:

def my_range(start, stop, step):
    yield from range(start, stop, step)

Now you don’t need an explicit loop for yielding the items of the range() generator one-by-one.

Leave a Reply