revive a generator

Paul Rudin paul.nospam at rudin.co.uk
Thu Oct 20 10:28:53 EDT 2011


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.








More information about the Python-list mailing list