Wednesday, 20 February 2019

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

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?



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

No comments:

Post a Comment