views:

542

answers:

5

How do you or together all values of a list in Python? I'm thinking something like:

or([True, True, False])

or if it was possible:

reduce(or, [True, True, False])
A: 

You can do this:

reduce(lambda a,b: a or b, [True, True, False])
Dustin
A: 

reduce should do it for you, shouldn't it?

>>> def _or(x, y):
...     return x or y
... 
>>> reduce(_or, [True, True, False])
True
PEZ
+23  A: 

The built-in function any does what you want:

>>> any([True, True, False])
True
>>> any([False, False, False])
False
>>> any([False, False, True])
True

any has the advantage over reduce of shortcutting the test for later items in the sequence once it finds a true value. This can be very handy if the sequence is a generator with an expensive operation behind it. For example:

>>> def iam(result):
...  # Pretend this is expensive.
...  print "iam(%r)" % result
...  return result
... 
>>> any((iam(x) for x in [False, True, False]))
iam(False)
iam(True)
True
>>> reduce(lambda x,y: x or y, (iam(x) for x in [False, True, False]))
iam(False)
iam(True)
iam(False)
True

If your Python's version doesn't have any(), all() builtins then they are easily implemented as Guido van Rossum suggested:

def any(S):
    for x in S:
        if x:
            return True
    return False

def all(S):
    for x in S:
        if not x:
            return False
    return True
Will Harris
+2  A: 
>>> all([True,False,True])
False
>>> any([True,False,True])
True

Python 2.5 and up (documentation)

orip
+5  A: 

No one has mentioned it, but "or" is available as a function in the operator module:

from operator import or_

Then you can use reduce as above.

Would always advise "any" though in more recent Pythons.

Ali A