revive a generator

Chris Angelico rosuav at gmail.com
Thu Oct 20 09:52:13 EDT 2011


On Fri, Oct 21, 2011 at 12:23 AM, Yingjie Lan <lanyjie at yahoo.com> wrote:
> 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?

If you're not generating very much, just use a list comprehension
instead; you can iterate over the list as many times as you like:

>>> g = [x*x for x in range(3)]
>>> for x in g: print(x)
0
1
4
>>> for x in g: print(x)
0
1
4

Of course, since this is Python 3, you need the parens on print, but I
assume you had something else you were doing with x.

ChrisA



More information about the Python-list mailing list