+6

Python: all(([]) returns True and any([]) returns False, why?

Why the all() function in python returns True when passed the empty list, whereas the any() function returns false when passed the same list? (I expected them to return False both, because the list is empty), someone can explain this behavior, and how the two functions work internally ? (Sorry for the mistakes if there is any, i'm not a native speaker 😀)

12/2/2019 2:17:29 PM

Saleh

9 Answers

New Answer

+10

I found this definition in the python docs: any() Return True if any element of the iterable is true. If the iterable is empty, it return False. all() Return True if all elements of the iterable are true. If the iterable is empty, it return True.

+5

I've asked the same a while ago. Good discussion there. :) https://www.sololearn.com/discuss/1397340/?ref=app

+5

This is how I think about the any() and all() functions: any() is like evaluating multiple "or" statements. It returns True if the first element is true or the second is true or the third is true or ... all() is like evaluating multiple "and" statements. It returns True if the first element is true and the second is true and the third is true and ... Now in logic, "or" behaves like addition and "and" behaves like multiplication. So I think of any([]) as an empty sum, which is 0 (False) and all([]) as an empty product, which is 1 (True).

0

That's an awesome finding! Very interesting, thanks for the question! Does anyone have any idea on why Python team chose to return True in the case of all([])? It seems counter-intuitive, but I bet it has some explanation.

0

Gonçalo Magalhaes can you guess what's in mind of python's team when they wrote these functions? 😅

0

Don't know, but perhaps that's documented somewhere.

0

Perhaps any() and or() are meant to be opposites, that’s why “empty any” is false and “empty all” is true.

0

سلام عليكم

-1

Funny how people end up writing in threads without even reading and thinking through what was written. EDIT: Oh, yeah, that's right, people not reading threads before they write something in them is actually a good thing - my mistake! So let me quickly downvote myself as well.