Next / Previous / Contents / TCC Help System / NM Tech homepage

23.10. The yield statement: Generate one result from a generator

A generator is any function or method that contains at least one yield statement. Generators are a special type of iterator; see Section 24.3, “Generators: Functions that can produce a sequence of values”. Here is the general form:

yield expression

Unlike ordinary functions or methods that use the return statement to return a single value, a generator is a mechanism that produces a sequence of zero or more values. Each execution of a yield statement produces an additional value. To signal the caller that there are no more values, use this raise statement:

raise StopIteration

As an example, here is a function that generates the sequence 0, 1, 2, ..., n-1, n, n-1, n-2, ..., 2, 1, 0.

>>> def updown(n):
...     '''Generate the values 0, 1, 2, ..., n-1, n, n-1, n-2, ...0.
...     '''
...     for answer in range(0,n):
...         yield answer
...     for answer in range(n, -1, -1):
...         yield answer
...     raise StopIteration
... 
>>> for x in updown(4):
...     print x,
... 
0 1 2 3 4 3 2 1 0