returning True, False or None

Peter Otten __peter__ at web.de
Fri Feb 4 15:04:15 EST 2005


Steven Bethard wrote:

> I have lists containing values that are all either True, False or None,
> e.g.:
> 
>      [True,  None,  None,  False]
>      [None,  False, False, None ]
>      [False, True,  True,  True ]
>      etc.
> 
> For a given list:
> * If all values are None, the function should return None.
> * If at least one value is True, the function should return True.
> * Otherwise, the function should return False.
> 
> Right now, my code looks like:
> 
>      if True in lst:
>          return True
>      elif False in lst:
>          return False
>      else:
>          return None
> 
> This has a light code smell for me though -- can anyone see a simpler
> way of writing this?

An attempt to short-circuit if possible:

def tristate(iterable):
    it = iter(iterable)
    for item in it:
        if item is not None:
            return item or True in it

Not as elegant as max(), but makes me wonder whether a max() that accepts an
additional upper_bound argument and returns upper_bound as soon as it
encounters a value >= upper_bound would be worth the effort.

Peter




More information about the Python-list mailing list