returning True, False or None

Jeff Shannon jeff at ccvcorp.com
Fri Feb 4 18:38:15 EST 2005


Jeremy Bowers wrote:

> On Fri, 04 Feb 2005 16:44:48 -0500, Daniel Bickett wrote:
> 
>>[ False , False , True , None ]
>>
>>False would be returned upon inspection of the first index, even
>>though True was in fact in the list. The same is true of the code of
>>Jeremy Bowers, Steve Juranich, and Jeff Shannon. As for Raymond
>>Hettinger, I can't even be sure ;)
> 
> Nope. 

Indeed.  Similarly for mine, which was really just a slight transform 
of Jeremy's (setting a return variable directly, instead of setting a 
flag that's later used to decide what to return):

 >>> def tfn(lst):
... 	answer = None
... 	for item in lst:
... 		if item is True: return True
... 		if item is False: answer = False
... 	return answer
...
 >>> list = [False, False, True, None]
 >>> tfn(list)
1
 >>> list = [None, False, False, None]
 >>> tfn(list)
0
 >>> list = [None, None, None, None]
 >>> print tfn(list)
None
 >>> >>>

The noted logical flaw *has* been present in a number of proposed 
solutions, however.

The key point to note is that one *must* examine the entire list 
*unless* you find a True; short-circuiting on False means that you may 
miss a later True.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list