How can I check that a list has one and only one truthy value?

It 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.


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:

  • Looks to make sure i has any true value
  • Keeps looking from that point in the iterable to make sure there is no other true value

Tags:

Python