This is an old copy of the Python FAQ. The information here may be outdated.

What is a generator?

A generator is a special kind of function that returns an iterator. It looks like a normal function, but values are returned to the caller using a yield statement instead of a return statement. When yield is called, the function is suspended and the yielded value is returned to the caller. The function is then resumed again the next time the caller asks for another value.

Generators are most often used with for-in and other operations that are designed to work with iterables:

>>> def gen():
...     yield 1
...     yield 2
...     for each in (3,4,5):
...         yield each
... 
>>> for val in gen():
...     print val
... 
1
2
3
4
5
>>> sum(gen())
15
>>> [str(i) for i in gen()]
['1', '2', '3', '4', '5']

You can also fetch values from a generator by hand. When you call a generator function, it returns a special generator object, and then immediately suspends itself. To run the generator, call its next method:

>>> x = gen()
>>> x
<generator object at 0x00AE63F0>
>>> x.next()
1
>>> x.next()
2
>>> x.next()
3
>>> x.next()
4
>>> x.next()
5

When the generator is exhausted, it raises a StopIteration exception:

>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

You can also create a generator using a generator expression that returns a generator. Like a list comprehension, a generator expression looks like a normal expression followed by a for expression defining a loop variable, a range or another iterable to loop over, and an optional if expression. The combined expression generates values for an enclosing function:

 
>>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
285
>>> x = (i*i for i in range(4))
>>> x.next()
0
>>> x.next()
1
>>> x.next()
4
>>> x.next()
9
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

Note that generator expressions must be written inside parentheses, but the extra parentheses can be left out when the expression is the sole argument to a function (as in the sum call in this example).

CATEGORY: general programming

 

A Django site. rendered by a django application. hosted by webfaction.