Generators in python; Through this tutorial, i am going to show you about python generators and how to use generators with python programs.
Python generators are used to create the iterators, but with a different approach. Generators are simple functions that return an iterable set of items, one at a time, in a unique way. There is a lot of things in building iterators in Python. We have to implement a class with __iter__() and __next__() method.
There is a lot of overhead in building an iterator in Python. we have to implement a class with
__next__() method, keep track of internal states, raise
StopIteration when there was no values to be returned etc.
How to create a generator in Python?
It is very easy to create a generator in Python programming. It is as easy as defining a normal function with
yield statement instead of a
The main difference between normal function and Python Generators is that the return statement terminates the function entirely; yield statement pauses the function saving all its states and variable values and later continues from there on successive calls.
See the following example of Generators in Python.
def createGenerator(): i = 1 print('Python') print(i) yield i i += 1 print('PHP') print(i) yield i i += 1 print('java') print(i) yield i gen = createGenerator() next(gen) next(gen) next(gen)
See the following output of above python program:
Python 1 PHP 2 java 3
One interesting thing to note in the above example is that the value of the variable i is remembered between each call.
Unlike any normal functions, the local variables are not destroyed when the function yields. In addition to that, the generator object can be iterated only once.
For Loops with Generators
Use the python for loop with Generators. And display the values with executing the next() function.
You can see the following example:
def createGenerator(): i = 1 print('Ronin') yield i i += 1 print('RedSkull') yield i i += 1 print('Rocket') yield i for g in createGenerator(): print(g)
See the following output of the above python program:
python 1 PHP 2 Java 3