Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to toggle between two values

Tags:

python

toggle

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?

like image 680
Yngve Avatar asked Jun 11 '12 20:06

Yngve


People also ask

How do you toggle between two values in Python?

from itertools import cycle myIterator = cycle(range(2)) myIterator. next() # or next(myIterator) which works in Python 3.

How do you toggle a number in Python?

The XOR example can be generalised to toggle between values a and b using x = x ^ (a ^ b) .

How do you do a between in Python?

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.


3 Answers

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, ... 
like image 91
Platinum Azure Avatar answered Sep 22 '22 13:09

Platinum Azure


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 
like image 33
g.d.d.c Avatar answered Sep 25 '22 13:09

g.d.d.c


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
like image 44
Levon Avatar answered Sep 25 '22 13:09

Levon