How do you get the logical xor of two variables in Python?
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
1. And logical xor is equivalent to bitwise xor when the domain is restricted to
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.