Python all () and bool () empty cases?

when using help (all), it returns:

all(iterable)=>bool
return True if bool(x) is True for all values x in the iterable.    
if the iterable is empty, return True

help (bool) returns:

bool(x) -> bool
 |  
 |  Returns True when the argument x is true, False otherwise.
 |  The builtins True and False are the only two instances of the class bool.
 |  The class bool is a subclass of the class int, and cannot be subclassed.

upon attempt:

>>>bool()
False

>>>all([])
True

My question is that all the input is an empty list / dict / tuple (i.e. an iterator), which is passed to bool ?? and how does it return True since it depends on bool?

+4
source share
4 answers

bool()never called if argument is all()empty. This is why documents point to all()empty entry behavior as a special case.

The behavior is bool() == Falsenot related to that all()anyway. By the way, Python boolhas a subclass int, which is why bool() == Falseit is necessary for compatibility with this int() == 0.

, , , all([]) True, . , x ,

all(x) == (bool(x[0]) and all(x[1:]))

all([]) == True - , x.

+13
all(iterable)

... documented ;

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

..., False , False.

, , , False, - True.

+7

[...] bool?

, "" bool(). bool . ? ! arent arent.

+6

, - :

def all(inp):
    return not any(not bool(x) for x in inp)

so the empty iterator is "valid." This makes sense and corresponds to similar concepts in logic - usually we say that a universal quantifier has some sentence over a region, even if the existential does not.

+2
source

Source: https://habr.com/ru/post/1546084/


All Articles