revive a generator

Terry Reedy tjreedy at udel.edu
Thu Oct 20 15:56:30 EDT 2011


On 10/20/2011 9:23 AM, Yingjie Lan wrote:

> it seems a generator expression can be used only once:

Generators are iterators. Once iterators raise StopIteration, they are
supposed to continue doing so.

A generator expression defines a temporary anonymous generator function 
that is called once to produce a generator and then deleted. It, like 
all comprehensions, is purely a convenient abbreviation.

>>>> g = (x*x for x in range(3))
        for x in g: print x
> 0 1 4
>>>> for x in g: print x #nothing printed

Define a named generator function (and add a parameter to make it more
flexible and useful and reuse it.

def g(n):
   for i in range(n):
     yield i*i

Then, "for x in g(3)", "for x in g(8)", "for x in g(y*x)", etc, as many 
times as you want. You might call it 'square' or even 'r_square' instead 
of 'g'.

-- 
Terry Jan Reedy




More information about the Python-list mailing list