returning True, False or None

Jeff Shannon jeff at ccvcorp.com
Fri Feb 4 15:27:52 EST 2005


Jeremy Bowers wrote:

> On Fri, 04 Feb 2005 10:48:44 -0700, Steven Bethard wrote:
> 
>>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.
> 
> 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

I'd modify this approach slightly...

def tfn(lst):
     answer = None
     for item in lst:
         if item is True: return True
         if item is False: answer = False
     return answer

But yeah, the original, straightforward way is probably enough clearer 
that I wouldn't bother with anything else unless lists might be long 
enough for performance to matter.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list