Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of all() in python

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

The documentation of all() reads that it returns True is all the elements are True/For an empty list. Why does all([ [ ] ]) evaluate to False? Because [ ] is a member of [ [ ] ], it should evaluate to True as well.

like image 313
xssChauhan Avatar asked Dec 09 '15 10:12

xssChauhan


3 Answers

The docstring for all is as follows:

all(iterable) -> bool

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

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

The other examples return True because the single item is no longer empty, so it is boolean True.

like image 97
Daniel Roseman Avatar answered Oct 11 '22 10:10

Daniel Roseman


>>all([])
True

because all iterables the list are True (there are zero iterables though)

>>all([[]])
False

there is one empty iterable (innermost empty list) which would evaluate to False

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

the only iterable here ( [[]] ) has one empty list inside of it, and hence evaluates to True

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

same as above

like image 2
Ayush Avatar answered Oct 11 '22 11:10

Ayush


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

all returns True if and only if each one of the elements of its argument evaluates to True.

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

In the second example, the list's only element is an empty list, which evaluates to False, therefore all returns False.

For all the other examples, the list's only element contains further lists, and therefore isn't empty and evaluates to True, so all has to return True.

like image 2
hlt Avatar answered Oct 11 '22 10:10

hlt