Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you apply 'or' to all values of a list in Python?

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])
like image 545
pupeno Avatar asked Dec 20 '08 19:12

pupeno


People also ask

What is any () and all () in Python?

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.


2 Answers

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
like image 156
Will Harris Avatar answered Oct 13 '22 23:10

Will Harris


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.

like image 44
Ali Afshar Avatar answered Oct 13 '22 23:10

Ali Afshar