# Can this be written more concisely in a functional style

Anton Vredegoor anton at vredegoor.doge.nl
Tue Nov 18 19:03:12 CET 2003

```mis6 at pitt.edu (Michele Simionato) wrote:

>def any(p, seq):
>    """Returns true if any element in seq satisfies predicate p."""
>    for elt in itertools.ifilter(p, seq):
>        return True
>     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
>     return True
>
>Since the "else" is unnecessary, it disturbs me, I get confused,
>I don't see why it is used (there is no break in the loop) and the
>code becomes much harder to read, for me. OTOH I am sure 99% of
>people would say "look, it is obvious, if elt is in the output
>of ifilter it will return True, else False (viceversa in the
>second case)". But may brain sees that the "else" is unncessary
>and immediately it is disturbed by th redundance.
>Am I the only one? ;)

Well, don't the multiple returns disturb you? I'd suggest this but
probably it's too clever:

from itertools import islice,ifilter

def any(predicate,seq):
return bool(list(islice(ifilter(predicate,seq),1)))

def test():
xs = 'abc123def456'
def fun(x):
print x
return x == '3'
print any(fun,xs)

if __name__=='__main__':
test()

Anton

```