Y
Y
Yura Khlyan2016-03-24 18:16:50
Python
Yura Khlyan, 2016-03-24 18:16:50

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

This confused me a little, and in the documentation it became clear that:
def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

Can anyone tell me why it was decided to return an empty object True?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2016-03-24
@deliro

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.

N
nirvimel, 2016-03-24
@nirvimel

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

With such a notation, the reasons for the corresponding behavior on empty lists immediately become obvious.

A
aRegius, 2016-03-25
@aRegius

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 question

Ask a Question

731 491 924 answers to any question