Difference between Generator function and Normal function
There are few points that can clear the difference between Generator Function and Normal Function.
- Normal function has only one return statement in the loop whereas generator function can use one or more yield statement in the loop.
- While calling the generator functions, the normal function take pause immediately and control has been transferred to the caller.
- Local variable and their states are remembered between successive calls of the functions.
- When the function terminates, StopIteration exception is raised automatically.
In the code section, incase of generator function, only yield statements are used in place of return statement and the remaining statements are just like normal function. There are some more points:
- Presence of yield statement shows that the function is not normal function but a generator
- Calling the function like normal functions, does not actually execute the function, but it creates an instance of the function.
- The next ( ) method, executes the code written up to first yield statement and then returns the value generated.
- When we call next () again, it will resume the processing of function counter, from the place where it was left last till the yield statement is met again.
Let’s take an example of producing squares of n numbers using iterator and generator.
Squares using generator
def Square (n):
for i in range (n):
yield i**2
The function can be invoked in following way
- for k in Square (6): print (k)
OUTPUT:
0
1
4
9
16
25
Same Code using iterator but replacing yield into return
def Square (n):
for i in range (n):
return i**2
Calling the function square
- for k in Square (6): print (k)
The above mentioned code results into
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
for k in Square (6):
TypeError: ‘int’ object is not iterable.
It’s because here Square( ) will just return only one integer object not a series of values.
Use generator to produce Fibonacci series
def Fibonacci (max):
a, b = 0, 1
while a <= max:
yield a
a, b = b, a + b
- for i in Fibonacci (100): print (i)
0 1 1 2 3 5 8 13 21 34 55 89
The generator can also be used to return a list of values
- L = list (Fibonacci (100))
- print L
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Advantages of using generator
- Generator functions are better in case of memory utilization and code performance because they allow the function to avoid doing all work at a time.
2 They provide a way to manually save the state during the running of loop. As the variables in function scope are saved and restored automatically.
* The Content stated above is for informational purpose only. Expert Software Team is not responsible if any part of content found meaningless in any manner or condition.