Restart generator when it is exhausted.

Chris Rebert clp2 at rebertia.com
Tue Apr 28 06:04:45 EDT 2009


On Tue, Apr 28, 2009 at 2:54 AM, Lacrima <Lacrima.Maxim at gmail.com> wrote:
> Hello!
>
> I am quite new to Python and I have maybe simple (or maybe not)
> question.
>
> Is it possible to restart generator when it is exhausted?

No. You have to make a new instance of the generator.

> What should I do to get the initial state of g? So if I do again g.next
> () I receive 'a'.

g = (i for i in a) #that is, make a fresh generator instance

> If it is not possible what are common techniques to use iterator or
> generator objects that allow restarting when it is needed?

There's itertools.cycle() --
http://docs.python.org/library/itertools.html#itertools.cycle

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list