Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

What Are Python Generators?

Give Feedback

Learn the basics of creating and using generators. In order to understand how asyncio works, it is important to have a basic understanding of how generators work. In this lesson, you’ll learn how to turn a regular function into a generator using the yield keyword.

You’ll also see a couple of examples like the one below that show how to create and use a generator to make a sequence of values.

def odds(start, stop):
    for odd in range(start, stop + 1):
        yield odd

Eddie on April 23, 2019

Not very important I guess, but I guess odds will give us even numbers if we use an even number as start and/or as end, won’t it? Something like this could help avoid that:

def odds_2(start, stop):
    if start % 2 == 0:
        start =+ 1
    for odd in range(start, stop+1, 2):
        yield odd

UBBA on May 15, 2019

Just an observation that instead of jumping to different applications -note that the creation of the directory and files can easily be done inside of Visual Studio Code and that interactive running of the code can be done inside of Python interactive (Jupyter) inside of Visual Studio Code.

Pygator on Sept. 14, 2019

Interesting, can there be multiple yield keywords in our generator or should we only use one per generator function?

Sam Ezebunandu on Dec. 6, 2019

@pygator. I have tried multiple yield statements in the same generator and it seems to work.

Jarrod on Jan. 21, 2020

Why didnt calling odds yield or return a value? Why did you have to call the next function to return a value?

Jarrod on Jan. 21, 2020

what was the purpose and what is the logic behine the if statement name == main ?

Become a Member to join the conversation.