Generator

This lesson discusses the concept of a generator in Python.

We'll cover the following...

Generator

Functions containing a yield statement are compiled as generators. Using a yield expression in a function’s body causes that function to be a generator. These functions return an object which supports the iteration protocol methods. The generator object created, automatically receives a __next()__ method. Going back to the example from the previous section we can invoke __next__ directly on the generator object instead of using next():

def keep_learning_asynchronous():
    yield "Educative"


if __name__ == "__main__":
    gen = keep_learning_asynchronous()

    str = gen.__next__()
    print(str)

You can execute the above code in the code widget below:

Press + to interact
def keep_learning_asynchronous():
yield "Educative"
if __name__ == "__main__":
gen = keep_learning_asynchronous()
str = gen.__next__()
print(str)

Also note, the snippet iter(gen) is gen returns True. Thereby, confirming that a generator function returns a generator object which is an iterator.

Press + to interact
def keep_learning_asynchronous():
yield "Educative"
if __name__ == "__main__":
gen = keep_learning_asynchronous()
print(iter(gen) is gen)

Recap

Remember the following about generators:

  • Generator functions allow us to procrastinate computing expensive values. We only compute the next value when required. This makes generators memory and compute efficient. They refrain from saving long sequences in ...