dizzyf dizzyf - 1 month ago 16
Python Question

Python XOR preference: bitwise operator vs. boolean operators

Is there a preferred method for doing a logical XOR in python?

For example, if I have two variables a and b, and I want to check that at least one exists but not both, I have two methods:

Method 1 (bitwise operator):

if bool(a) ^ bool(b):
do x


Method 2 (boolean operators):

if (not a and b) or (a and not b):
do x


Is there an inherent performance benefit to using either one? Method 2 seems more "pythonic" but Method 1 looks much cleaner to me. This related thread seems to indicate that it might depend on what variable types
a
and
b
are in the first place!

Any strong arguments either way?

Answer

One of the alternative way to achieve it is using any() and all() like:

if any([a, b]) and not all([a, b]):
    print "Either a or b is having value"

But based on the performance, below are the results:

  1. Using any() and all(): 0.542 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "any([a, b]) and not all([a, b])"
    1000000 loops, best of 3: 0.542 usec per loop
    
  2. Using bool(a) ^ bool(b): 0.594 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "bool(a) ^ bool(b)"
    1000000 loops, best of 3: 0.594 usec per loop
    
  3. Using (not a and b) or (a and not b): 0.0988 usec per loop

    moin@moin-pc:~$ python -m "timeit" "a='a';b='b';" "(not a and b) or (a and not b)"
    10000000 loops, best of 3: 0.0988 usec per loop
    

Clearly, your (not a and b) or (a and not b) is more efficient. Approximately 6 times efficient then others.