"and" and "or" on every item in a list

Tim Chase python.list at tim.thechases.com
Tue Oct 30 00:45:20 CET 2007


> Is this the best way to test every item in a list?
> 
> def alltrue(f,l):
>     return reduce(bool.__and__,map(f,l))
> 
> def onetrue(f,l):
>     return reduce(bool.__or__,map(f,l))
> 
>>>> alltrue(lambda x:x>1,[1,2,3])
> False
>>>> alltrue(lambda x:x>=1,[1,2,3])
> True

As of Python2.5, there's an any() and all() function built into
the language.

  >>> any(map(lambda x: x>1, [1,2,3]))
  >>> all(map(lambda x: x>1, [1,2,3]))

Implementations for older versions are given at

http://docs.python.org/lib/built-in-funcs.html

You can adjust the "if" test in the example code so that it calls
your function...something like

  def my_any(f, iterable):
    for element in iterable:
      if f(element):
        return True
    return False

  def my_all(f, iterable):
    for element in iterable:
      if not f(element):
        return False
    return True

The advantage of the code in the docs is that it
short-circuits...there's no need to reduce the entire list if an
early item triggers the condition (a "true" early in an "any" or
a "false" early in an "all").

While you can use a reduce(bool.__and__, thing) call, I more
frequently see it as reduce(operator.or_, thing)

Just a few ideas,

-tkc






More information about the Python-list mailing list