revive a generator

Yingjie Lan lanyjie at yahoo.com
Thu Oct 20 21:46:30 EDT 2011


----- Original Message -----
> From: Paul Rudin <paul.nospam at rudin.co.uk>
> To: python-list at python.org
> Cc: 
> Sent: Thursday, October 20, 2011 10:28 PM
> Subject: Re: revive a generator
>> Yingjie Lan <lanyjie at yahoo.com> writes:
>>> Hi,
>>>> it seems a generator expression can be used only once:
>>>>>>> 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
>>>>>>>>> Is there any way to revive g here?
>>>> 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?


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /