Search code examples
pythonbitwise-operators

How to apply bitwise operator to compare a list of objects


Suppose I have a long list of objects (say, a list of numpy matrices of bool elements) foo = [a, b, c], that I want to compare with some bitwise operator, to get something like a | b | c.

If I could use this bitwise operation as a function, say a bitwiseor function, I could simply do this with bitwiseor(*foo). However, I was not able to find whether the bitwise or can be written in such functional form.

Is there some handy way to handle this kind of problem? Or should I just use a loop to compare all the elements cumulatively?


Solution

  • Using the functional method in operator in combination with functools.reduce:

    >>> import operator, functools
    >>> functools.reduce(operator.or_, [1, 2, 3])
    3