revive a generator

Paul Rudin paul.nospam at rudin.co.uk
Fri Oct 21 03:27:54 EDT 2011


Yingjie Lan <lanyjie at yahoo.com> writes:

> ----- Original Message -----
>> From: Paul Rudin <paul.nospam at rudin.co.uk>

>> Generators are like that - you consume them until they run out of
>> values. You could have done [x*x for x in range(3)] and then iterated
>> over that list as many times as you wanted.
>> 
>> A generator doesn't have to remember all the values it generates so it
>> can be more memory efficient that a list. Also it can, for example,
>> generate an infinite sequence.
>> 
>> 
> Thanks a lot to all who answered my question. 
> I am still not sure why should we enforce that 
> a generator can not be reused after an explicit 
> request to revive it?

The language has no explicit notion of a request to "revive" a
generator. You could use the same syntax to make a new generator that
yeilds the same values as the one you started with if that's what you
want. 

As we've already discussed if you want to iterate several times over the
same values then it probably makes sense to compute them and store them
in e.g. a list (although there are always trade-offs between storage use
and the cost of computing things again).






More information about the Python-list mailing list