for_some(), for_all()?
Raymond Hettinger
vze4rx4y at verizon.net
Thu Sep 23 02:12:14 EDT 2004
[Michael Hoffman]
> There are some recipes for any() and all() in the itertools documents
> that do what you want:
>
> http://www.python.org/doc/current/lib/itertools-example.html
>
> >>> 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
speed.
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