Check if only one variable in a list of variables is set

Deon picture Deon · Jun 23, 2009 · Viewed 7.1k times · Source

I'm looking for a simple method to check if only one variable in a list of variables has a True value. I've looked at this logical xor post and is trying to find a way to adapt to multiple variables and only one true.

Example

>>>TrueXor(1,0,0)
True

>>>TrueXor(0,0,1)
True

>>>TrueXor(1,1,0)
False

>>>TrueXor(0,0,0,0,0)
False

Answer

Andrew Hare picture Andrew Hare · Jun 23, 2009

There isn't one built in but it's not to hard to roll you own:

def TrueXor(*args):
    return sum(args) == 1

Since "[b]ooleans are a subtype of plain integers" (source) you can sum the list of integers quite easily and you can also pass true booleans into this function as well.

So these two calls are homogeneous:

TrueXor(1, 0, 0)
TrueXor(True, False, False)

If you want explicit boolean conversion: sum( bool(x) for x in args ) == 1.