How do you apply 'or' to 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])
The Python any() and all() functions evaluate the items in a list to see which are true. The any() method returns true if any of the list items are true, and the all() function returns true if all the list items are 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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With