Name

The yield Statement

Synopsis

yield expression

Optional in 2.2; enable with from _ _future_ _ import generators. Suspend function state and return expression. On the next iteration, the function’s prior state is restored, and control resumes immediately after the yield statement. Use a return statement with no value to end the iteration, or simply fall off the end of the function:

def generate_ints(N):
    for i in xrange(N):
        yield i

Generators and iterators

In 2.2, functions containing a yield statement are compiled as generators; when called, they return a generator object that supports the iterator interface (i.e., a next( ) method).

Iterators are objects returned by the iter(X) built-in function; they define a next( ) method, which returns the next item in the iteration or raises a StopIteration exception to end the iteration. Classes may provide an _ _iter_ _ method to overload the iter(X) built-in function call; if defined, the result is used to step through objects in for loops, rather than the traditional _ _getitem_ _ indexing overload scheme.

Get Python Pocket Reference, Second 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.