The Python Oracle

Is only one element in boolean list true?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Is Only One Element In Boolean List True?
00:38 Accepted Answer Score 12
01:26 Thank you

--

Full question
https://stackoverflow.com/questions/4018...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #bitmanipulation

#avk47



ACCEPTED ANSWER

Score 12


Python bool subclass from int so you don't need to do any conversion:

>>> sum([True, False, False])
1
>>> sum([True, True, True])
3

This solution doesn't short-circuit however ... there are some cases where you might want to be able to bail out earlier:

result = 0
for item in boolean_iterable:
    result += item
    if result > 1:
        break  # Short-circuit early

However, unless your boolean iterables are really large, and you expect to short-circuit frequently, I would expect this to perform worse than the sum in the average case (which can push the loop to more optimized code).

Also if you're looking for clever ways to do this with bitwise arithmetic, you can use xor in a reduce operation:

>>> from functools import reduce
>>> import operator
>>> reduce(operator.xor, [True, False, False], False)
True
>>> reduce(operator.xor, [True, False, True], False)
False
>>> reduce(operator.xor, [], False)
False
>>> reduce(operator.xor, [True], False)
True

But I wouldn't advise using this version :-)