Python is the most versatile programming language in recent times. It provides many built-in modules, functions, and keywords to perform various tasks. Python provides the ability to create generator functions. A generator function also allows you to create an iterator function.
In Python, a generator function is defined as the normal function using the def keyword. However, it uses the yield keyword instead of return to produce a value. The yield keyword is a built-in keyword in Python that returns the value from the function. The difference between a return and a yield statement is that it does not terminate the flow of function; rather, it pauses the execution of the function, returns the value to the caller, and resumes the execution from the last yield. Any function that contains the yield keyword inside the implementation body automatically becomes a generator function. This article explains the Python generator in detail with some simple examples.
Example 1: Simple Generator Function
In this example, we will create a simple generator function that contains a yield keyword. In the following example, every yield keyword returns a value. The execution of the generator function is paused on every yield keyword, and the value is returned to the caller. After returning the value, the program flow is resumed from the last yield keyword. To access the values from the generator function, we will create an iterator for the function using a for loop.
def myFunc():
#using yield keyword
yield "LinuxHint"
yield "Python 3.8"
yield 1
#code to access the generator function
for i in myFunc():
print(i)
Output
The generator function always returns the value in the form of a generator object. The generator object values can also be accessed by using the next method instead of defining a for loop.
Let us now modify the above example and use the next() function instead of the for loop. The next() function is a built-in function that takes the generator object as an argument.
def myFunc():
#using yield keyword
yield "LinuxHint"
yield "Python 3.8"
yield 1
#storing the generator object in variable val
val =myFunc()
print("The output is:")
#printing the first yield value
print(next(val))
#printing the second yield value
print(next(val))
#printing the third yield value
print(next(val))
Output
Example 2: Simple Generator Function to Generate Even Numbers
In this next example, we will create a generator function that takes a list of integers as an argument and identifies the even numbers in the list. An even number is a number that, when divided by two, returns zero as the remainder. In the following example, the program is implemented in two different ways, i.e., with the next() function and the for loop.
def evenFunc(myList):
for i in myList:
if(i%2==0):
yield i
#declaring a list of numbers
myList = [1,3,2,4,7,8,9,45,44,22,12,14,90]
#storing the generator object in variable val
val =evenFunc(myList)
print("Using next function to access yield value:")
#printing the first yield value
print(next(val))
#printing the second yield value
print(next(val))
#printing the third yield value
print(next(val))
#printing the fourth yield value
print(next(val))
#printing the fifth yield value
print(next(val))
#printing the sixth yield value
print(next(val))
#printing the seventh yield value
print(next(val))
#printing the eighth yield value
print(next(val))
print("Using for loop to access the yield values:")
for i in evenFunc(myList):
print(i)
Output
Example 3: Generator Function to Implement Simple Calculator
In the given example, we have defined two number variables, i.e., num1 and num2. We are calculating sum, difference, multiplication, division, and average values. Each calculated value is returned using the yield keyword.
def calc():
#defining a num1 variable
num1 = 10
#defining a num2 variable
num2 = 20
#calculating sum
yield num1+num2
#calculating difference
yield num2-num1
#performing multiplication
yield num1*num2
#performing division
yield num2/num1
#calculating average value
yield (num1+num2)/2
print("The following are the result values:")
for i in calc():
print(i)
Output
Generator Expression
Python provides a minimal way of defining generator functions known as a generator expression. This is a short way of defining the generator function. A generator expression consists of two parts. The first part of the expression is a yield value, and the second part is a for loop.
Let us now see an example using a generator expression. In the following example, we will calculate the cube value of the first six numbers in the list.
#storing the generator object in val variable
val= (x*x*x for x in range(6))
#printing values using next()
print(next(val))
print(next(val))
print(next(val))
print(next(val))
print(next(val))
print(next(val))
Output
Conclusion
Python generator functions are defined in the same way as normal functions, but they contain a yield statement. A yield statement is a Python built-in keyword that returns the value from the function. This article explained generator functions and expressions in Python with some simple examples.