In Python, the built-in functions all
and any
return True
and False
respectively for empty iterables. I realise that if it were the other way around, this question could still be asked. But I'd like to know why that specific behaviour was chosen. Was it arbitrary, ie. could it just as easily have been the other way, or is there an underlying reason?
(The reason I ask is simply because I never remember which is which, and if I knew the rationale behind it then I might. Also, curiosity.)
One property of
any
is its recursive definitionThat means
The equality is correct for any
x
if and only ifany([])
is defined to be False. Similar forall
.This is really more of a comment, but code in comments doesn't work very well.
In addition to the other logical bases for why
any()
andall()
work as they do, they have to have opposite "base" cases so that this relationship holds true:If
iterable
is zero-length, the above still should hold true. Thereforewhich is equivalent to
And it would be very surprising if
any([])
were the one that is true.How about some analogies...
You have a sock drawer, but it is currently empty. Does it contain any black sock? No - you don't have any socks at all so you certainly don't have a black one. Clearly
any([])
must return false - if it returned true this would be counter-intuitive.The case for
all([])
is slightly more difficult. See the Wikipedia article on vacuous truth. Another analogy: If there are no people in a room then everyone in that room can speak French.Mathematically
all([])
can be written:There is considerable debate about whether vacuous statements should be considered true or not, but from a logical viewpoint it makes the most sense:
Also from the article:
Defining a "vacuously true" statement to return false in Python would violate the principle of least astonishment.
The official reason is unclear, but from the docs (confirming @John La Rooy's post):
See also the CPython-implementation and comments.