returning True, False or None

Daniel Bickett dbickett at gmail.com
Fri Feb 4 16:44:48 EST 2005


I'm seeing a consistent problem in most of these approaches.
Verbalized, the logic of the OP's original code reads as such:

If True is in the list *at all*, return True.
Otherwise, if False is in the list *at all*, return False.
Otherwise, return None.

So if we used Alex Martelli's code:

> for val in lst:
>    if val is not None:
>        return val
> return None

and the list was:

[ 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 ;)

The original OP's code, on the other hand, inadvertently searches
through the list twice where once would have sufficed, causing a
needless performance pitfall. The following applies the OP's initial
logic while only iterating once:

>>> def boolhunt( items ):
	falseExists = False
	for item in items:
		if item is True:
			return True
		elif item is False and not falseExists:
			falseExists = True
	if falseExists:
		return False
>>> l1 = [ True , None , None , False ]
>>> l2 = [ None , False , False , None ]
>>> l3 = [ False , True , True , True ]
>>> boolhunt( l1 )
True
>>> boolhunt( l2 )
False
>>> boolhunt( l3 )
True

It isn't elegant or clever, but it gets the job done :)

-- 
Daniel Bickett
dbickett at gmail.com
http://heureusement.org/



More information about the Python-list mailing list