returning True, False or None
Jeremy Bowers
jerf at jerf.org
Fri Feb 4 08:01:16 EST 2005
On Fri, 04 Feb 2005 10:48:44 -0700, 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
Yes, I see the smell, you are searching the list multiple times. You
could bail out when you can:
seenFalse = False
for item in list:
if item: return True
if item is False: seenFalse = True
if seenFalse:
return False
return None
But I'd submit that if four item lists are your common case, that your
original code is significantly easier to understand what it is doing. This
can be alleviated with an appropriate comment on the chunk of code I gave
you, though.
More information about the Python-list
mailing list