bitwise operations between elements in a list
You can use reduce
with operator.ior
:
>>> from operator import ior
>>> lst = [1, 17, 1]
>>> reduce(ior, lst)
17
And as suggested by @DSM in comments the numpy equivalent will be:
>>> import numpy as np
>>> arr = np.array(lst)
>>> np.bitwise_or.reduce(arr)
17
This works for numpy reduce:
>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
Without importing anything, neither numpy
nor operator.ior
, as suggested in the other answers:
a = [1,17,1]
reduce(lambda x,y: x | y, a)
Edit: However, when I benchmarked different options, this was faster:
a = [1,17,1]; b = 0
for x in a: b |= x
This second option also has the advantage that it works in Python 3, from which reduce
has been eliminated (although it can still be imported from functools
).