Python Forum

Full Version: effective means to flip boolean values?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there a method or something to easily flip a Boolean value from False to True or vice versa?
You use not to do that, obviously.
ndc85430 idea expressed in code:

>>> spam = True
>>> spam = not spam
>>> spam
False
>>> spam = not spam
>>> spam
True
Another possibility is to use itertools.cycle(). This is useful, if there are more than two values to flip:

>>> from itertools import cycle
>>> switch = cycle([True, False]).__next__
>>> spam = switch()
>>> spam
True
>>> spam = switch()
>>> spam
False
>>> spam = switch()
>>> spam
True
>>> switch = cycle(['ON', 'STANDBY', 'OFF']).__next__
>>> spam = switch()
>>> spam
'ON'
>>> spam = switch()
>>> spam
'STANDBY'
>>> spam = switch()
>>> spam
'OFF'
>>> spam = switch()
>>> spam
'ON'
(Aug-24-2019, 08:16 PM)perfringo Wrote: [ -> ]ndc85430 idea expressed in code:

>>> spam = True
>>> spam = not spam
>>> spam
False
>>> spam = not spam
>>> spam
True
Another possibility is to use itertools.cycle(). This is useful, if there are more than two values to flip:

>>> from itertools import cycle
>>> switch = cycle([True, False]).__next__
>>> spam = switch()
>>> spam
True
>>> spam = switch()
>>> spam
False
>>> spam = switch()
>>> spam
True
>>> switch = cycle(['ON', 'STANDBY', 'OFF']).__next__
>>> spam = switch()
>>> spam
'ON'
>>> spam = switch()
>>> spam
'STANDBY'
>>> spam = switch()
>>> spam
'OFF'
>>> spam = switch()
>>> spam
'ON'


Thank you! That looks super useful!