8.4. All of Nothing¶
The all() built-in function accepts a sequence value, such as a list, and returns True if all the values in that sequence are “truthy.” It returns False if one or more values are “falsey.” You can think of the function call all([False, True, True]) as equivalent to the expression False and True and True .
You can use all() in conjunction with list comprehensions to first create a list of Boolean values based on another list and then evaluate their collec- tive value. For example, enter the following into the interactive shell:
>>> spam = [67, 39, 20, 55, 13, 45, 44]
>>> [i > 42 for i in spam]
[True, False, False, True, False, True, True]
>>> all([i > 42 for i in spam])
False
>>> eggs = [43, 44, 45, 46]
>>> all([i > 42 for i in eggs])
True
The all() utility returns True if all numbers in spam or eggs are greater than 42.
But if you pass an empty sequence to all() , it always returns True . Enter the following into the interactive shell:
>>> all([])
True
It’s best to think of all([]) as evaluating the claim “none of the items in this list are falsey” instead of “all the items in this list are truthy.” Otherwise, you might get some odd results. For instance, enter the following into the interactive shell:
>>> spam =[]
>>> all([i> 42 for i in spam])
True
>>> all([i< 42 for i in spam])
True
>>> all([i== 42 for i in spam])
True
This code seems to be showing that not only are all the values in spam (an empty list) greater than 42 , but they’re also less than 42 and exactly equal to 42 ! This seems logically impossible. But remember that each of these three list comprehensions evaluates to the empty list, which is why none of the items in them are falsey and the all() function returns True .