O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generators and yield

If a function uses the yield keyword, it defines an object known as a generator. A generator is a function that produces values for use in iteration. For example:

def count(n):
     print "starting to count"
     i = 0
     while i < n:
          yield i
          i += 1
      return

If you call this function, you will find that none of its code executes. For example:

>>> c = count(100)
>>>

Instead of the function executing, an iterator object is returned. The iterator object, in turn, executes the function whenever next() is called. For example:

>>> c.next()
0
>>> c.next()
1

When next() is invoked on the iterator, the generator function executes statements until it reaches a yield statement. The yield statement produces a result at which point execution of the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required