Solution using NOT
If the values are Boolean, the fastest approach is to use the not operator:
>>> x = True >>> x = not x
Subtraction Solution
If the values are numeric, then subtracting from the sum is a simple and quick way to switch values:
>>> A = 5 >>> B = 3 >>> total = A + B >>> x = A >>> x = total - x
XOR Solution
If the value switches between 0 and 1, you can use a bitwise exclusive-or :
>>> x = 1 >>> x ^= 1 >>> x 0 >>> x ^= 1 >>> x 1
The technique generalizes to any pair of integers. The xor-by-one step is replaced by xor-by-precomputed-constant:
>>> A = 205 >>> B = -117 >>> t = A ^ B
(This idea was introduced by Nick Coglan and later summarized by @zxxc.)
Dictionary solution
If the values are hashable, you can use a dictionary:
>>> A = 'xyz' >>> B = 'pdq' >>> d = {A:B, B:A} >>> x = A >>> x = d[x]
Conditional Expression Solution
The slowest way is to use a conditional expression :
>>> A = [1,2,3] >>> B = [4,5,6] >>> x = A >>> x = B if x == A else A >>> x [4, 5, 6] >>> x = B if x == A else A >>> x [1, 2, 3] >>> x = B if x == A else A >>> x [4, 5, 6]
Solution using itertools
If you have more than two values, the itertools.cycle () function provides a general quick way to switch between sequential values:
>>> import itertools >>> toggle = itertools.cycle(['red', 'green', 'blue']).next >>> toggle() 'red' >>> toggle() 'green' >>> toggle() 'blue' >>> toggle() 'red' >>> toggle() 'green' >>> toggle() 'blue'
Note that in Python 3, the next() method was changed to __next__() , so the first line will now be written as toggle = itertools.cycle(['red', 'green', 'blue']).__next__