Generator oddity

Duncan Booth duncan.booth at invalid.invalid
Fri May 1 08:53:01 EDT 2009


opstad at batnet.com wrote:

>>>> it1 = gen()
>>>> it2 = gen()
>>>> list(c1 + c2 for c1 in it1 for c2 in it2)
> ['aa', 'ab', 'ac']
> 
> Why does this last list only have three elements instead of nine?

First time through the c1 in it1 loop you use up all of the it2 values.
Second and third times through the c1 in it1 loop the it2 generator is 
still exhausted: you need to create a new generator each time if you want 
to repeat its values.


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list