[Python-ideas] Break the dominance of boolean values in boolean context

Steven D'Aprano steve at pearwood.info
Thu Sep 15 00:44:13 CEST 2011


MRAB wrote:

> What should any([]) return?

I'm not sure I understand the question, because any([]) already has an 
answer, and changing it would be a backwards-incompatible change. So I 
don't quite understand the point of the question: the answer is "exactly 
what it already returns".

 >>> any([])
False

Likewise for all:

 >>> all([])
True

This is known as "vacuous truth":

https://secure.wikimedia.org/wikipedia/en/wiki/Vacuous_truth


As far as justifying the results returned by any() and all(), the 
decision to return False and True respectively seems to work well for 
me. I have rarely, if ever, needed the opposite behaviour:

if not mylist or any(mylist):
     ...

if mylist and all(mylist):
     ....


so, at least for me, the behaviour of all() and any() seems like the 
right behaviour.


However, I point out that if the argument is an iterator instead of a 
sequence, it's significantly harder:

try:
     flag = bool(next(it))
except StopIteration:
     flag = False  # instead of True
else:
     flag = all(it)


Perhaps all() and any() should take an optional argument to return if 
the iterable is empty?




-- 
Steven




More information about the Python-ideas mailing list