Search code examples
pythonlistbooleanboolean-operations

or boolean function as function argument


Given

a = [1, 2, 3, 4]
b = [10, 1, 20, 30, 4]

I would like to check if any of the elements in a is present in b.

>>> [i in b for i in a]
Out[45]: [True, False, False, True]

The code above does part of the job. The next step could be a reduce. However, I did not get the code below working without my own implementation of the or function.

def is_any_there(a, b):
    one_by_one = [i in b for i in a]

    def my_or(a,b):
        if a or b:
            return True
        else:
            return False
    return reduce(my_or, one_by_one)

How can I avoid the rewriting of the or function?


Solution

  • is_there_any just reimplements the any function, available since Python 2.5:

    any(x in b for x in a)
    

    Further, my_or is already available as operator.or_ in the standard library.