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?
from itertools import cycle myIterator = cycle(range(2)) myIterator. next() # or next(myIterator) which works in Python 3.
The XOR example can be generalised to toggle between values a and b using x = x ^ (a ^ b) .
Python between() function with Categorical variable If we pass a string or non-numeric variable to the Pandas between() function, it compares the start and end values with the data passed and returns True if the data values match either of the start or end value.
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, ...
You can accomplish that with a generator like this:
>>> def alternate(): ... while True: ... yield 0 ... yield 1 ... >>> >>> alternator = alternate() >>> >>> alternator.next() 0 >>> alternator.next() 1 >>> alternator.next() 0
You can use the mod (%
) operator.
count = 0 # initialize count once
then
count = (count + 1) % 2
will toggle the value of count between 0 and 1 each time this statement is executed. The advantage of this approach is that you can cycle through a sequence of values (if needed) from 0 - (n-1)
where n
is the value you use with your %
operator. And this technique does not depend on any Python specific features/libraries.
e.g.
count = 0
for i in range(5):
count = (count + 1) % 2
print(count)
gives:
1
0
1
0
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With