Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book