Python all() and bool() empty cases?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3
--
Chapters
00:00 Python All() And Bool() Empty Cases?
00:37 Answer 1 Score 6
00:54 Answer 2 Score 2
01:16 Answer 3 Score 7
01:38 Accepted Answer Score 13
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/2442...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #builtin
#avk47
ACCEPTED ANSWER
Score 13
bool() is never invoked if all()'s argument is empty. That's why the docs point out the behavior of all() on an empty input as a special case.
The behavior bool() == False is irrelevant to what all() does in any case. By the way, in Python bool is a subclass of int, so bool() == False is necessary to be compatible with that int() == 0.
As to why, e.g., all([]) is True, it's to preserve useful identities. Most importantly, for any non-empty sequence x it's desirable that
all(x) == (bool(x[0]) and all(x[1:]))
and all([]) == True is the only result allowing that identity to hold for all values of x.
ANSWER 2
Score 7
all(iterable)
...is documented to be equivalent to;
def all(iterable):
for element in iterable:
if not element:
return False
return True
...which returns False if and only if any value in the list converts to False.
Since there is no element in the list you pass in, no element converts to False, and the result of the function call is True.
ANSWER 3
Score 6
[…] what's passed to bool?
Nothing – and not the “nothing” of bool(). bool is never called. Is every element in an empty sequence truthy? Yes! There aren’t any that aren’t, after all.
ANSWER 4
Score 2
My guess is that it's implemented something like:
def all(inp):
return not any(not bool(x) for x in inp)
so an empty iterator is "vacuously true." This makes sense, and corresponds with similar notions in logic -- we usually say that a universal quantifier holds of some proposition over a domain even if an existential one doesn't.