The behavior of all () in python

>>all([]) True >>all([[]]) False >>all([[[]]]) True >>all([[[[]]]]) True 

The all () documentation reads that it returns True, all True / elements for an empty list. Why are all ( [[]] ) evaluated as False? Since [] is a member of [[]] , it must also evaluate to True.

+6
source share
3 answers
 >>all([]) True 

because all iterations of the list are True (however there are zero iterations)

 >>all([[]]) False 

there is one empty iterable (the innermost empty list) that will evaluate to False

 >>all([[[]]]) True 

the only iterability here ( [[]] ) has one empty list inside it and therefore evaluates to True

 >>all([[[[]]]]) >>True 

as mentioned above

+1
source

The dockstone for all as follows:

all(iterable) -> bool

Return True if bool (x) is True for all x values ​​in iterable. If iterability is empty, return True.

This explains the behavior. [] is empty iterable, so all returns True. But [[]] not empty iterable; it is an iterable containing one item, an empty list. Calling bool on this empty list returns False; therefore the whole expression is False.

Other examples return True because one element is no longer empty, so it is a Boolean value of True.

+10
source

Lists in Python evaluate to True if and only if they are not empty (see, for example, this ).

all returns True if and only if each of the elements of its argument is True .

In the first example, your list is empty, and all returns True .

In the second example, only the list item is an empty list that evaluates to False , so all returns False .

For all other examples, only the list item contains additional lists and, therefore, is not empty and takes the value True , so all should return True .

+1
source

All Articles