Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading