Answer the question
In order to leave comments, you need to log in
Strange behavior of a built-in function. Is not it?
Good day.
Recently I came across a rather strange result of executing a standard function:
any([]) == False
all([]) == True
def all(iterable):
for element in iterable:
if not element:
return False
return True
True
?
Answer the question
In order to leave comments, you need to log in
At first glance it may seem illogical, but there is logic here.
When is all used? When we check that all variables in an iterable object are True (no matter what kind). To put it another way, we can say: "all indicates that all objects in the list are not False". Because The list is empty, which means there are no objects in it that are False.
With any similar logic. "any indicates that there is at least one True element in the list." Because the list is empty - it means that it does not contain at least one object that is True.
In the documentation, the implementation of these functions is written in an imperative style, apparently for clarity (IMHO, the visibility is rather controversial). You can try to write them in a functional style - this is not difficult (let me remind you that all
this is a conjunction of all elements of a list / iterator cast to a boolean type, and any
, accordingly, a disjunction).
import operator
all = lambda xs: reduce(operator.__and__, map(bool, xs), True)
any = lambda xs: reduce(operator.__or__, map(bool, xs), False)
The all() function uses the and operator , which in turn corresponds to the mathematical multiplication symbol ' * ' . function any() - operator or (mathematical addition symbol ' + ' )
Any something can be divided into components: Something and Nothing . For example, 5 = 5 + 0
So, let's say the all() function takes Something as an argument (any True ). Keeping in mind that all() operates
on ' * ' , we can break this Trueto True * 1 . Those. in the case with the function all() Nothing , it turns out, takes the value 1/ True .
Accordingly, keeping in mind that any() works with ' + ' , we can split this True into True + 0 . Those. in the case of the any() function Nothing , it turns out, takes the value 0/ False .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question