Generator oddity

Pascal Chambon chambon.pascal at wanadoo.fr
Fri May 1 08:34:32 EDT 2009


opstad at batnet.com a écrit :
> I'm a little baffled by the inconsistency here. Anyone have any
> explanations?
>
>   
>>>> def gen():
>>>>         
> ...   yield 'a'
> ...   yield 'b'
> ...   yield 'c'
> ...
>   
>>>> [c1 + c2 for c1 in gen() for c2 in gen()]
>>>>         
> ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
>
>   
>>>> list(c1 + c2 for c1 in gen() for c2 in gen())
>>>>         
> ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
>
>   
>>>> 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?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
>   
When you use "for c2 in gen()]",  at each loop of c1, a new gen is 
instanciated and looped-over to continue building the list.
Whereas when you use "for c2 in it2)", it's always the same instance of 
gen which is used (it2), so after 3 loops on c2 this instance is 
exhausted, and the following iterations on c1 (and then attempts of 
looping on c2) don't give anything because the looping on c2 gives an 
exception "StopIteration".

Regards,
pascal


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090501/0be879db/attachment.html>


More information about the Python-list mailing list