Best way to generate alternate toggling values in a loop?

Alex Martelli aleax at mac.com
Thu Oct 18 09:47:54 EDT 2007


Grant Edwards <grante at visi.com> wrote:
   ...
> I like the solution somebody sent me via PM:
> 
> def toggle():
>     while 1:
>         yield "Even"
>         yield "Odd"

I think the itertools-based solution is more elegant:

toggle = itertools.cycle(('Even', 'Odd'))

and use toggle rather than toggle() later; or, just use that
itertools.cycle call inside the expression instead of toggle().


Alex
 



More information about the Python-list mailing list