for_some(), for_all()?
Larry Bates
lbates at swamisoft.com
Wed Sep 22 13:04:05 EDT 2004
Use list comprehension and then test for what you want:
for_some
result=[x for x in lst if <insert your test here>]
if result:
#
# At least some of the items passed the test
#
else:
#
# None passed
#
for_all
result=[x for x in lst if <insert your test here>]
if len(result) == len(lst):
#
# All items passed the test
#
else:
#
# At least one didn't pass
#
I think it is easier to read and maintain.
Larry Bates
"aurora" <aurora00 at gmail.com> wrote in message
news:opseqmpvg86yt6e7 at news.cisco.com...
>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)?
>
>
More information about the Python-list
mailing list