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.)
Perl 6 also takes the position that
all()
andany()
on empty lists should serve as sane base-cases for their respective reduction operators, and thereforeall()
is true andany()
is false.That is to say,
all(a, b, c)
is equivalent to[&] a, b, c
, which is equivalent toa & b & c
(reduction on the "junctive and" operator, but you can ignore junctions and consider it a logical and for this post), andany(a, b, c)
is equivalent to[|] a, b, c
, which is equivalent toa | b | c
(reduction on the "junctive or" operator -- again, you can pretend it's the same as logical or without missing anything).Any operator which can have reduction applied to it needs to have a defined behavior when reducing 0 terms, and usually this is done by having a natural identity element -- for instance,
[+]()
(reduction of addition across zero terms) is 0 because 0 is the additive identity; adding zero to any expression leaves it unchanged.[*]()
is likewise 1 because 1 is the multiplicative identity. We've already said thatall
is equivalent to[&]
andany
is equivalent to[|]
-- well, truth is the and-identity, and falsity is the or-identity -- x and True is x, and x or False is x. This makes it inevitable thatall()
should be true andany()
should be false.To put it in an entirely different (but practical) perspective,
any
is a latch that starts off false and becomes true whenever it sees something true;all
is a latch that starts off true and becomes false whenever it sees something false. Giving them no arguments means giving them no chance to change state, so you're simply asking them what their "default" state is. :)all([]) == True
: zero out of zero - checkany([]) == False
: anyone? nobody - failI believe
all([])==True
is generally harder to grasp, so here are a collection of examples where I think that behaviour is obviously correct:any
andall
have the same meaning in python as everywhere else:any
is true if at least one is trueall
is not true if at least one is not trueI think of them as being implemented this way
not sure they are implemented that way though
For general interest, here's the blog post in which GvR proposes any/all with a sample implementation like gnibbler's and references quanifiers in ABC.