How do you get the logical xor of two variables in Python?
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
You can always use the definition of xor to compute it from other logical operations:
(a and not b) or (not a and b)
But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is:
bool(a) ^ bool(b)
The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since bool
is just a subclass of int
, but is implemented to only have the values 0
and 1
. And logical xor is equivalent to bitwise xor when the domain is restricted to 0
and 1
.
So the logical_xor
function would be implemented like:
def logical_xor(str1, str2):
return bool(str1) ^ bool(str2)
Credit to Nick Coghlan on the Python-3000 mailing list.
Bitwise exclusive-or is already built-in to Python, in the operator
module (which is identical to the ^
operator):
from operator import xor
xor(bool(a), bool(b)) # Note: converting to bools is essential