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

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to