Python

How to Use the Python Generator Functions Howto

The generator function works similarly to the normal function. But when it is time to return a value, we use the yield function instead of return in Python. The generator function works with the help of generator objects. In this article, we will learn the significant difference between the normal and the generator functions.

Syntax

Yield expression

Python yield returns the generator object. These are the special objects that help in getting the value. Due to this, it is iterated.

Tools of Python Generator

Generator Function:

These functions are defined as a normal function “def”, but they use the yield keyword instead of return. Thus, the result is obtained one at a time.

Generator Expressions:

These expressions work similarly to the list comprehensions. However, they differ in one aspect. As they return an object, it shows the result only when demanded instead of producing the lists of results.

Example

A simple illustration to enlighten the concept of generators is explained below. At first, we will define the generator, as we used to define a simple function. After that, we will print the string and will use the yield keyword to return the value.

Def gen()

Yield 10

Where gen() is the name of a generator, every time the yield is called, it returns the value to be displayed.

To obtain the output on Linux, go to the Ubuntu terminal and write the following command:

$ python3  ‘/home/aqsa/Documents/resulttemp.py’

Where python3 is a keyword used, we have used the path of a file having the extension of “.py” which shows that the file is written in Python.

The output is as follows:

You can see that the yield function has returned each value line by line.

Difference Between the Generator and the Normal Functions

Here, we have taken an example to explain the difference between a regular function and the generator having a yield function. At first, the normal function is defined:

Def function()

In this function, only a string is printed as an output. Second, we have defined a generator.

Def generator()

This will yield the string as an output. After defining both the function and generator, we will allow the function calls and let them print.

Print (generator())

Now, we will view the output by executing the same practice described above.

From the output, you can see that the result of the normal function is obtained, but the generator has shown some sort of error. So, there is another way of obtaining the output by using the generator’s object. We have taken the same example as described above to explain the functionality. The whole code is the same, but the method of printing of the generator is replaced with the following code:

Print (next(generator()))

This command will help in retrieving the string written in the generator.

Now, from the output, you can view that instead of display the error message. The desired output is obtained in the form of a string.

Get/Read The Values From the Generator Function

There are different functions that help in obtaining the output from the generator. We will discuss two of them one by one.

List ()

A list is an object that contains its values inside the brackets. This object is iterable and displays the values with iterations. In the generator, the lists will display all the values that the generator holds. Besides the list, for loop () and next () functions are also used to present the output.

Consider an example in which we have defined a generator named “function” in which we have used a for loop for the numbers to iterate. A mathematical operation is performed in this function. The generator function receives a value that is passed as a parameter when this function is called.

For x in range(n):

If(x%2==0):

Yield x

This is the core code of the generator function:

Then, after finding the modulus, the resultant value is returned by using yield. Next, the further procedure of printing is done through the list function that is as follows.

Print(list(num))

This function provides the output in the form of a list. For example, the output is shown below:

Next()

The following function will display the next value in any list, array or, object. If we use the next function in any empty array, then it will show an error message. So, to get the fine value, the array or list should not be empty. The same mathematical operation is applied in this example. However, the method of printing is different. Since 20 is the number passed as a parameter, the numbers will be obtained till 20 is attained in the output. We completed seven rounds.

Print(next(num))

Now, we will see the output. Note, all the even numbers are obtained:

Fibonacci Number Series and the Generators

Fibonacci series is the sequence of numbers acquired by adding the last two numbers before it. We have used the following example to understand the functionality of generators. In this function, we have taken two variables that store two numeric values in them. We have also taken a count variable. This function will work in such a way that it will check if the value of the count is smaller than the current number. Next, it will add the previous two numbers, and it will save them in the next one. The process will remain till the number 7 is reached. Finally, the result is obtained by using the for loop ().

The output of the affixed above code is as follows:

0, 1, 1, 2, 3, 5, 8

Function call by using Yield

This is the example of calling the function by using the yield. In comparison, we have used the square function in the generator.

Def getsquare(n):

Yield test(i)

Through the yields function, we have used the function call to get the answer:

The required output is given below:

0, 1, 4, 9, 14, 25, 36, 49, 64, 81

Conclusion

In this article, we have explained the examples of a generator, how we can obtain the output, and the difference between the generator and the normal function.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.