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? Right now, I am just iterating across the list and manually checking:
def only1(l) true_found = False for v in l: if v and not true_found: true_found=True elif v and true_found: return False #"Too Many Trues" return true_found
This seems inelegant and not very pythonic. Is there a cleverer way to do this?
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list. count() function.
It's the simplest and fastest way to do this. If you want to check that a variable is explicitly True or False (and is not truthy/falsy), use is ( if variable is True ). If you want to check if a variable is equal to 0 or if a list is empty, use if variable == 0 or if variable == [] .
A boolean list is a list that has no holes and contains only the boolean values true and false (see Chapter Booleans). In function names we call boolean lists blist for brevity. A boolean list (``blist'') is a list that has no holes and contains only true and false .
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 valueIt depends if you are just looking for the value True
or are also looking for other values that would evaluate to True
logically (like 11
or "hello"
). If the former:
def only1(l): return l.count(True) == 1
If the latter:
def only1(l): return sum(bool(e) for e in l) == 1
since this would do both the counting and the conversion in a single iteration without having to build a new list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With