Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 371
Matthew Scouten Avatar asked May 28 '13 20:05

Matthew Scouten


People also ask

How do you check if a value is in a list Python?

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.

How do you know if one variable is true?

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 == [] .

Can a list contain Boolean?

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 .


2 Answers

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
like image 168
Jon Clements Avatar answered Sep 23 '22 21:09

Jon Clements


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.

like image 40
David Robinson Avatar answered Sep 24 '22 21:09

David Robinson