+ 7

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 😀)

2nd Dec 2019, 2:17 PM
Salih Benlalla
Salih Benlalla - avatar
9 Antworten
+ 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.
2nd Dec 2019, 2:37 PM
Lothar
Lothar - avatar
+ 5
I've asked the same a while ago. Good discussion there. :) https://www.sololearn.com/discuss/1397340/?ref=app
2nd Dec 2019, 3:06 PM
HonFu
HonFu - avatar
+ 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).
2nd Dec 2019, 9:20 PM
Njeri
Njeri - avatar
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.
2nd Dec 2019, 5:56 PM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
0
Gonçalo Magalhaes can you guess what's in mind of python's team when they wrote these functions? 😅
2nd Dec 2019, 7:42 PM
Salih Benlalla
Salih Benlalla - avatar
0
Don't know, but perhaps that's documented somewhere.
2nd Dec 2019, 7:58 PM
Gonçalo Magalhaes
Gonçalo Magalhaes - avatar
0
Perhaps any() and or() are meant to be opposites, that’s why “empty any” is false and “empty all” is true.
2nd Dec 2019, 9:44 PM
Prof. Dr. Zoltán Vass
0
سلام عليكم
3rd Dec 2019, 11:03 PM
Moussa Debba
Moussa Debba - avatar
- 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.
2nd Dec 2019, 10:05 PM
HonFu
HonFu - avatar