>>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.
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.
>>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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With