In python, I have a list that should have one and only one truthy value (that is, bool(value) is True
). Is there a clever way to check for this
One that doesn't require imports:
def single_true(iterable):
i = iter(iterable)
return any(i) and not any(i)
Alternatively, perhaps a more readable version:
def single_true(iterable):
iterator = iter(iterable)
# consume from "i" until first true or it's exhausted
has_true = any(iterator)
# carry on consuming until another true value / exhausted
has_another_true = any(iterator)
# True if exactly one true found
return has_true and not has_another_true
This:
i
has any true value