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])
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])
reduce should do it for you, shouldn't it?
>>> def _or(x, y):
... return x or y
...
>>> reduce(_or, [True, True, False])
True
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
>>> all([True,False,True])
False
>>> any([True,False,True])
True
Python 2.5 and up (documentation)
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.