missing 'xor' Boolean operator

Anthony Tolle anthony.tolle at gmail.com
Wed Jul 15 14:53:23 EDT 2009


On Jul 14, 2:25 pm, "Dr. Phillip M. Feldman" <pfeld... at verizon.net>
wrote:
> Current Boolean operators are 'and', 'or', and 'not'.  It would be nice to
> have an 'xor' operator as well.

My $0.02 on this discussion: There would be nothing gained by having
non-bitwise XOR operator.  You can't short-circuit XOR, because you
must evaluate all operands to produce a result.  Consequently,
returning the "true" item also doesn't make much sense.  XOR is closer
to the the logical NOT operator than it is to AND or OR.

Here's my own take on a function that can handle any number of
arguments (it should probably raise an exception for 0 or 1 arguments,
but I'm lazy):

def xor(*operands):
    if operands:
        operands = list(operands)
        a = bool(operands.pop(0))
        while operands:
            b = bool(operands.pop(0))
            if a:
                if b:
                    a = False
            elif b:
                a = True
        return a
    return False



More information about the Python-list mailing list