Can this be written more concisely in a functional style

Jeremy Fincher tweedgeezer at hotmail.com
Tue Nov 18 05:59:47 EST 2003


jcb at iteris.com (MetalOne) wrote in message news:<92c59a2c.0311172340.544faac6 at posting.google.com>...
> Maybe my post was not clear.
> I want a means to test if there exists an element in the list that
> satisfies a predicate.

Sure there is.  The code that you showed was an excellent way to do
so.

> Actually, when I word it that way, I guess what I want is PEP 289,
> universal and existential qualifiers.
> 
> I guess I'll have to wait.

Why?  Why not just stuff the code you wrote into an appropriately
named function and use that?

Anyway, here are more efficient implementations:

def any(p, seq):
    """Returns true if any element in seq satisfies predicate p."""
    for elt in itertools.ifilter(p, seq):
        return True
    else:
        return False

def all(p, seq):
    """Returns true if all elements in seq satisfy predicate p."""
    for elt in itertools.ifilterfalse(p, seq):
        return False
    else:
        return True

Jeremy




More information about the Python-list mailing list