for_some(), for_all()?

Raymond Hettinger vze4rx4y at
Thu Sep 23 08:12:14 CEST 2004

[Michael Hoffman]
> There are some recipes for any() and all() in the itertools documents
> that do what you want:
>  >>> import itertools, timeit, operator
>  >>> def any(seq, pred=bool):
> ...     "Returns True if pred(x) is True at least one element in the
> iterable"
> ...     return True in imap(pred, seq)

I chose that one for the docs because it gave the best balance of clarity and

For pure speed, the following is faster and gives short-circuit behavior:

>>> from itertools import ifilter
>>> def any(seq, pred=None):
...     for elem in ifilter(pred, seq):
...         return True
...     return False

Raymond Hettinger

More information about the Python-list mailing list