any(), all() and empty iterable
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Tue Apr 14 21:47:35 EDT 2009
On Tue, 14 Apr 2009 17:54:14 +0000, John O'Hagan wrote:
> Agreed; having absorbed the answers to my original question, I now
> understand why all('Robinson Crusoe' in books for books in []) - or with
> any object in place of the string, or indeed just all([]) - doesn't
> return False, but, vacuous truth notwithstanding (and it's apparently a
> not uncontroversial notion), it doesn't seem fair to return True without
> so much as a how's-your-father. ;)
I don't see why you call it unfair. It is very fair. You're just
unfortunate that *your* use-case was one of the times that the alternate
behaviour would be better, *and* you didn't know about vacuous truths. If
you had known, you wouldn't have been surprised -- but that's true about
everything. It is, in fact, a vacuous truth :)
http://en.wikipedia.org/wiki/Analytic-synthetic_distinction
I would be far more upset by all() raising an exception on an empty list!
And it is very simple to create a version of all() which doesn't return
true for vacuous truths.
def all2(sequence_or_iterator):
"""Like all() but returns False for vacuous truths."""
# Untested
it = iter(sequence_or_iterator)
try:
if not it.next(): return False
except StopIteration:
return False
return all(it)
> An exception, or at least a specific mention of the case of empty
> iterables in the docs (as Tim Chase suggested), would have baffled me
> less than my program telling me that the same items were both ubiquitous
> and entirely absent from a list of sets!
>
> Of course, it's possible people out there depend on the present
> behaviour.
You better believe it.
--
Steven
More information about the Python-list
mailing list