any(), all() and empty iterable

Luis Alberto Zarrabeitia Gomez kyrie at uh.cu
Sun Apr 12 06:46:32 CEST 2009


Quoting John O'Hagan <mail at johnohagan.com>:

> Hi,
> 
> I was getting some surprising false positives as a result of not expecting 
> this:
> 
> all(element in item for item in iterable)
> 
> to return True when 'iterable' is empty. 
> 
[...]
> any(element in item for item in iterable)
> 
> which returns False when 'iterable' is empty.

The "any" and "all" functions for python2.5 mirror the existential[1] and
uiniversal[2] quantifiers from predicate logic. In layman terms, 

"any" returns true if there exists at least one element in the collection for
which the predicate ("element in item" in your case) is true. If the collection
is empty, there are no elements, and in particular, there can be no elements
that satisfy your predicate (returns false). This function/quantifier is well
defined on an empty set.

"all" returns true if for every element in the collection, the predicate holds.
If you have an empty set, there is no way that the predicate could evaluate to
false, thus, it return true. While this may seem arbitrary at first, keep in
mind that one expects the phrase "all this values in this set are true" to mean
the same as "there are no false values in this set", i.e, all(x for x in list)
== not any(not x for x in list). So, the universal quantifier/python's "all"
function may be easier to understand as: "returns true if there is no element in
the set that for which the predicate is false".

These would be "any" and "all" implementations in pure python:

def any(elements):
    for element in elements:
        if element:
            return True
    return False

def all(elements):
    for element in elements:
        if not element:
            return False
    return True

You may also want to look at [3]

K.

P.S: Forgive my english. I'm falling asleep... I hope I made sense.

[1] http://en.wikipedia.org/wiki/Existential_quantification
[2] http://en.wikipedia.org/wiki/Universal_quantification
[3] http://en.wikipedia.org/wiki/Vacuous_truth

-- 
Luis Zarrabeitia
Facultad de Matemática y Computación, UH
http://profesores.matcom.uh.cu/~kyrie


-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu




More information about the Python-list mailing list