How Do You Use a Generator and the Yield Keyword in Python?

Problem scenario
You want to use a generator in Python.  You also want to use the yield keyword in Python.  How do you use these?

Solution
The short answer to the question about how do you use a generator is to create a function with the yield keyword (source Programiz.com).  "Both yield and return will return some value from a function."  (The source of this quote is Programiz.com.)

A Python generator is in essence a coroutine.  Coroutines enable intelligent control between two different parts of a program (e.g., a cooperative process that interleaves the invocation of one part of the code to return to another section of the code and thus re-enter it with a dynamic value that has been precomputed).  A generator has discrete steps of iteration which can be executed with the "next" keyword.  The yield keyword is like a return statement without necessarily being final.  The execution of a generator will provide intermediate values with its yield statement(s) and continue with calls with the "next" keyword.   The "yield" and "next" keywords are important for using the generator feature in Python.  This program below illustrates how to use the yield and next keywords; this simple program below also demonstrates how to use a generator.

# Call this program gen.py.  Run it with "python gen.py" (with no quotes).
# Examine the output and you will see how yield works like a return statement without the finality.
# This program uses a Python generator.  Note that you do not need the use the word "generator"
# in the function definition.  It can be helpful for readability, but Python knows what to do by merely
# using the word "yield" inside the function.

def continual_generator_func():
  yield 1
  yield 2
  yield 3
  yield 4 
tempobject = continual_generator_func();
a = next(tempobject)
next(tempobject)
next(tempobject)
b = next(tempobject)
print(a)
print(b)

Leave a comment

Your email address will not be published. Required fields are marked *