for_some(), for_all()?
Alex Martelli
aleaxit at yahoo.com
Wed Sep 22 13:37:01 EDT 2004
aurora <aurora00 at gmail.com> wrote:
> I am trying to test a list to see if some or all elements pass a test. For
> example I can use reduce() to test if any element is 0.
>
> >>> lst = [1,2,0,3]
> >>> test = lambda x: x == 0
> >>> reduce(operator.__or__,[test(x) for x in lst])
> True
>
> However I bet reduce() does not exploit the short circuit logic. Also it
> is a little clumsy to create another list to pass into reduce. Is there
> some equivalent of
>
> for_some(test, lst)
> or
> for_all(test, lst)?
Simplest:
def for_some(test, lst):
for item in lst:
if test(item): return True
def for_all(test, lst):
for item in lst:
if not test(item): return False
return True
You can play tricks, but you can't beat the simplicity of these, and
even with the cleverest tricks you can't beat their speed by much. And
simplicity is a great quality for software to have.
Alex
More information about the Python-list
mailing list