4.3 Using any() and all() as reductions
The any()
and all()
functions provide boolean reduction capabilities. Both functions reduce a collection of values to a single True
or False
. The all()
function ensures that all items have a true value; the any()
function ensures that at least one item has a true value. In both cases, these functions rely on the Pythonic concept of ”truish”, or truthy: values for which the built-in bool()
function returns true
. Generally, ”falsish” values include False
and None
, as well as zero, an empty string, and empty collections. Non-false values are true.
These functions are closely related to a universal quantifier and an existential quantifier used to express mathematical logic. We may, for example, want to assert that all elements in a given collection have a property. One formalism for this could look like the following:
We read this as for all x in S, the function, Prime(x), is true. We’ve used the universal quantifier...