Introduction to Python Function Generator
A function in a python programming language is defined as a set of statements inside the body of the function that can be executed any number of times in the program by just calling the function name instead of those set of statements. A normal function usually executes until it finds return statements, exceptions or the end of the function.
A generator- function is the same as a normal function in python, but in the normal function, it can return only one value, whereas, in the generator function, it can return series of values by using the “yield” keyword. In the normal function, the return statement work is to return the control of execution to that point where the function was called. In the generator function, the yield statement work is to transfers the control, which is temporary where it can return more than one value. In simple words, a generator function is a way of creating iterators, which means the function returns an iterator which we can iterate over.
How Does Python Generator Function Work?
In python, a generator function is one of the special functions that return the values in a loop, unlike lists, but these iterators do not store their contents in memory. The only difference between the normal function and generator function is that instead of a normal function return statement, use a yield statement that yields multiple values instead of a single value like a normal function.
The above code is the syntax of how the generator function looks like In; this code is similar to normal function syntax, but there is a yield statement instead of the return statement. When an interpreter notices a yield statement instead of a return, then it takes it as a generator function and returns an iterator.
The return statement in a normal function is the last call, but the yield temporarily suspends the execution of the function and then resumes. The return statement exits the function where yield sends the value back to the caller.
In Python, generators are a very easy and attractive topic that is easy is easy to implement. It takes multiple statements to return values in a normal function, but if the generator function is used, it helps in the reusability of code, which saves the number of lines. Let’s look at the example below for calculating the power of 2’s.
def _init_(self, max = 0 ):
self. max = max
self.n = 0
if self.n > self. max:
result = 2 ** self.n
So the above example can be written using a generator function instead of a normal function in a few lines.
def power_two(max = 0 ):
n = 0
while n < max:
yield 2 ** n
This generator function has two main methods one to stop the iteration and the other to get the next value from the generator, and they are declared as iter() or close(), and next() or send() respectively. There is another method in the generator function known as the throw() method, which throws an exception with the generator.
Examples to Implement Python Function Generator
Below are the example of Python Function Generator:
a = 1
a += 1
a += 1
for x in generator_funciton():
Explanation: The above example is for the yield statement, which gives the series of output from1 to 3. The value of “a” to be returned was 1, so to print those series of values, we need to use for statement to get the sequence of the series. So by using the yield statement every time, the value a” is incremented by 1 and is returned using the yield statement.
So the generator objects or series of values are either returned using for a loop as we did in the above example, and the other option is to use the next() method to get the series of values or generator objects.
x = simpleGeneratorFun()
print"First value", x.next();
The .throw() method is used to throw exceptions with the generator.
num = 0
i = (yield num)
if i is not None:
num = i
num += 1
# Skip single-digit inputs
if num // 10 == 0:
temp = num
reversed_num = 0
while temp != 0:
reversed_num = (reversed_num * 10) + (temp % 10)
temp = temp // 10
if num == reversed_num:
pal_gen = infinite_palindromes()
for i in pal_gen:
digits = len(str(i))
if digits == 5:
pal_gen.throw(ValueError("We don't like large palindromes"))
pal_gen.send(10 ** (digits))
Explanation: Generator function in python is one of the important topics in case if we are working on huge data sets or data streams or CSV files (a set of data separated by commas). Using the generator function, we can yield a series of values from huge data sets like a number of rows, etc. The below piece of code is a small example of using a generator function on data sets or large CSV files.
for row in open(“article.txt”,”r”):
generator_csv = csv_reader(“article.txt”)
count_rows = 0
for rows in generator_csv:
print(“Count of number of rows”, count_rows)
Explanation: It will Count the number of rows present in the text file.
The above example outputs the count of a number of rows from the file “article.txt”. We first open the file in reading mode and then using the yield statement in for loop.
In python, the generator function which use a yield statement instead of a return statement to get a series of values instead of getting a single value. A generator function is very easy to implement; it’s memory-efficient because generators are memory friendly for implementing a sequence of values, whereas, in the normal function, it will use memory for the entire sequence of values to be returned.
This is a guide to Python Function Generator. Here we discuss a brief overview of Python Function Generator and its Examples along with its Code Implementation. You can also go through our other suggested articles to learn more –