Generator oddity

Andre Engels andreengels at gmail.com
Fri May 1 16:31:44 CEST 2009


On Fri, May 1, 2009 at 4:25 PM, Dave Angel <davea at ieee.org> wrote:

> The problem is in it2, which is initialized only once.  Thus the second time
> you're going through the c2 loop, it doesn't have any more values.
>
> If you need the indirection provided by those it1 and it2, you need to
> postpone the function evaluation, at least for it2.
>
> I'd do
> it1 = gen
> it2 = gen
>
> list(c1 + c2 for c1 in it1() for c2 in it2())
> or more simply:
> [c1 + c2 for c1 in it1() for c2 in it2()]

Another possibility would be to use the outcome of looping through the
generator rather than the generator itself:

it1 = list(gen())
it2 = list(gen())
[c1 + c2 for c1 in it1() for c2 in it2()]


-- 
André Engels, andreengels at gmail.com



More information about the Python-list mailing list