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 ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.