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

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

Leave a Comment