Skip to content
Advertisement

How to toggle a value?

What is the most efficient way to toggle between 0 and 1?

Advertisement

Answer

Solution using NOT

If the values are boolean, the fastest approach is to use the not operator:

JavaScript

Solution using subtraction

If the values are numerical, then subtraction from the total is a simple and fast way to toggle values:

JavaScript

Solution using XOR

If the value toggles between 0 and 1, you can use a bitwise exclusive-or:

JavaScript

The technique generalizes to any pair of integers. The xor-by-one step is replaced with a xor-by-precomputed-constant:

JavaScript

(This idea was submitted by Nick Coghlan and later generalized by @zxxc.)

Solution using a dictionary

If the values are hashable, you can use a dictionary:

JavaScript

Solution using a conditional expression

The slowest way is to use a conditional expression:

JavaScript

Solution using itertools

If you have more than two values, the itertools.cycle() function provides a generic fast way to toggle between successive values:

JavaScript

Note that in Python 3 the next() method was changed to __next__(), so the first line would be now written as toggle = itertools.cycle(['red', 'green', 'blue']).__next__

Advertisement