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.
Syntax:
def generator_function(arguments):
statement(s)
yield [value]
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.
class power_two:
def _init_(self, max = 0 ):
self. max = max
def _iter_(self):
self.n = 0
return self
def _next_(self):
if self.n > self. max:
raise StopIteration
result = 2 ** self.n
self.n+=1
return result
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
n+ =1
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:
Example #1
Code:
def generator_funciton():
a = 1
print("First value")
yield a
a += 1
print("Second value")
yield a
a += 1
print("Third value")
yield a
for x in generator_funciton():
print(x)
Output:
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.
Example #2
Code:
def simpleGeneratorFun():
yield 1
yield 2
yield 3
x = simpleGeneratorFun()
print"First value", x.next();
print"Second value",x.next();
print"Third value",x.next();
Output:
Example #3
The .throw() method is used to throw exceptions with the generator.
Code:
def infinite_palindromes():
num = 0
while True:
if is_palindrome(num):
i = (yield num)
if i is not None:
num = i
num += 1
def is_palindrome(num):
# Skip single-digit inputs
if num // 10 == 0:
return False
temp = num
reversed_num = 0
while temp != 0:
reversed_num = (reversed_num * 10) + (temp % 10)
temp = temp // 10
if num == reversed_num:
return True
else:
return False
pal_gen = infinite_palindromes()
for i in pal_gen:
print(i)
digits = len(str(i))
if digits == 5:
pal_gen.throw(ValueError("We don't like large palindromes"))
pal_gen.send(10 ** (digits))
Output:
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.
Code:
def csv_reader("article.txt"):
for row in open("article.txt","r"):
yield row
generator_csv = csv_reader("article.txt")
count_rows = 0
for rows in generator_csv:
count_rows+= 1
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.
Conclusion
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.
Recommended Articles
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 –
- Advantages of Programming in Python
- What is Recursive Function in Python?
- Introduction to Python Range Function
- Top 7 Methods of Python Set Function
Related Courses