Monthly Archives: February 2012

Python Generators

Generators are one of important features of python. A generator is a function that when called executes up to a ‘yield’ command. When we call a generator function, it returns a generator object. This object stores information about the original function and the values of the variables in the function and the location of the code to run next. So next time the function is called, it resume from the point it had stopped and continue execution.

Here is an example:

>>> def test():

print ‘Hai’

yield 1

print ‘Hello’

yield 2

To execute the function, we have to use the ‘next()’ method.

>>> call = test()

>>> call.next()

Hai

1

>>> call.next()

Hello

2

>>> call.next()

Traceback (most recent call last):

File “<stdin>” line 1, in ?

StopIteration

We can use for loop in the generator, which works by calling a.next() and assigning the obtained value to i.

>>> call = test()

>>> for i in place:

print i

Hai

1

Hello

2

Here is a program for printing factorials as an example for generators:

 # A simple factorial program using python generators with iterations

>>>  def factorial(n):

 count = 1

 fact = 1

 while count <= n:

 yield fact

 count = count + 1

 fact = fact * count

 >>> print “Factorial program using generators.”

 >>> for i in factorial(5):

 print i


Output:

Factorial program using generators.

1

2

6

24

120

The WordPress.com Blog

The latest news on WordPress.com and the WordPress community.