Why Python built in "all" function returns True for empty iterables?
Why Python built in "all" function returns True for empty iterables?
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Question
01:22 Accepted answer (Score 36)
03:03 Answer 2 (Score 10)
03:28 Answer 3 (Score 2)
04:23 Answer 4 (Score 1)
04:41 Thank you
--
Full question
https://stackoverflow.com/questions/1197...
Accepted answer links:
[using logic]: http://bytes.com/topic/python/answers/47...
Answer 2 links:
[all()]: http://docs.python.org/library/functions...
Answer 4 links:
[http://en.wikipedia.org/wiki/Empty_set]: http://en.wikipedia.org/wiki/Empty_set
[http://en.wikipedia.org/wiki/Vacuous_tru...]: http://en.wikipedia.org/wiki/Vacuous_tru...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
ACCEPTED ANSWER
Score 36
This is expressed as "For all X in S, X is true". If S is empty, there are no X. However, the truth statement remains True, because for all X, X was true... there just aren't any X!
Here is a explanation using logic.
Consider two sets A and B where A+B is the union of the two sets.
If any(A+B) = True -> any(A) or any(B) = True but we cannot assert either any(A)=True or any(B)=True.
If any(A+B) = False -> any(A) = False and any(B) = False.
If all(A+B) = True -> all(A)=True and all(B)=True
if all(A+B) = False -> all(A)=False or all(B)=False but we cannot assert either all(A)=False or all(B)=False.
Now instead of B, let's add the empty set Ø to A. We want to come up logic such that adding the empty set does not change the values of all() or any(), since A+Ø=A.
any(A+Ø) = any(A) or any(Ø)
any(Ø) must be False, so that if any(A) is True, any(A+Ø) is True, and if any(A) is False, any(A+Ø) is False.
all(A+Ø) = all(A) and all(Ø)
if all(A) is True, all(A+Ø) is True. Therefore, all(Ø) is True.
ANSWER 2
Score 11
all() (documented to "Return True if all elements of the iterable are true (or if the iterable is empty).") is equivalent to the following:
def all(iterable):
for element in iterable:
if not element:
return False
return True
Since there are no elements, it will skip the loop and return True.
ANSWER 3
Score 2
This comes from the mathematical logic.
"everything is true of the elements of the empty set" (http://en.wikipedia.org/wiki/Empty_set)
ANSWER 4
Score 1
Because all elements are True. When there are no elements, you can say that 'all elements are ... anything'