Search code examples
pythontoggle

How to toggle between two values?


I want to toggle between two values in Python, that is, between 0 and 1.

For example, when I run a function the first time, it yields the number 0. Next time, it yields 1. Third time it's back to zero, and so on.

Sorry if this doesn't make sense, but does anyone know a way to do this?


Solution

  • Use itertools.cycle():

    from itertools import cycle
    myIterator = cycle(range(2))
    
    myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 0
    myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 1
    # etc.
    

    Note that if you need a more complicated cycle than [0, 1], this solution becomes much more attractive than the other ones posted here...

    from itertools import cycle
    mySmallSquareIterator = cycle(i*i for i in range(10))
    # Will yield 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, ...