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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

The WordPress.com Blog

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

%d bloggers like this: