-->

Create generators using yield keyword

 

What is a generator ?

 python generator is a function it returns an iterable object.

What  is  iterator ?

Iterator is an object which store the sequence of items that can be accessed/implemented via "__next__" or "next" functions.

What is iteration ?

The process of getting item from an iterator.
Note: Iterators are lazy in nature. they can be used only once

Lets create a generator for prime numbers


def prime_number_generator():
for i in range(1, 8):
count = 0
for j in range(1, i+1):
if (i % j ==0):
count+=1
if count == 2:
yield i

Lets Test our generator. 

We use "next" method to get item from generator. If we use all items in a generator and try to use "next" again we get "StopIteration" error.
In [1]: prime_number_generator
Out[1]:

In [2]: primes = prime_number_generator()

In [3]: primes
Out[3]:

In [4]: primes.next()
Out[4]: 2

In [5]: primes.next()
Out[5]: 3

In [6]: primes.next()
Out[6]: 5

In [7]: primes.next()
Out[7]: 7

In [8]: primes.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
in ()
----> 1 primes.next()

StopIteration:

Lets use generator in a "for" loop

In [1]: primes = prime_number_generator()

In [2]: for prime in primes:
...: print prime,
...:
2 3 5 7


Buy a product to Support me