Best way to generate alternate toggling values in a loop?

Iain King iainking at gmail.com
Thu Oct 18 15:48:00 CEST 2007


On Oct 18, 2:29 am, Grant Edwards <gra... at visi.com> wrote:
> On 2007-10-17, Debajit Adhikary <debaj... at gmail.com> wrote:
>
> > # Start of Code
>
> > def evenOdd():
> >     values = ["Even", "Odd"]
> >     state = 0
> >     while True:
> >         yield values[state]
> >         state = (state + 1) % 2
>
> I'd replace the last line with
>
>           state ^= 1
>
> to save a couple instructions, but I spend too much time
> working with micoroprocessors running on clocks measured in the
> KHz.
>
> There are probably other more Pythonic ways...
>


I always use:

           state = 1 - state

for toggles.  I doubt it's much more pythonic though :)

Iain




More information about the Python-list mailing list