Reputation: 567
I have a of list of bitwise elements, e.g. [1,1,1], and I want to do a bitwise OR operation between every element in the list. So, e.g.
for [1,1,1] do
1 | 1 | 1 = 1
or for [1,17,1] do
1 | 17 | 1 = 17
How can I do this without looping? Numpy's bitwise_or only seems to work on 2 arrays. Is there a bitwise & or | that works on every element, similar to sum, or np.mean? Thanks.
Upvotes: 17
Views: 16984
Reputation: 89204
In Python 3, reduce
is no longer a built-in function. functools.reduce
can be used in conjunction with operator.or_
instead.
from functools import reduce
import operator
l = [1, 17, 1]
result = reduce(operator.or_, l)
print(result) # 17
Alternatively, the following solution can be used just for ints:
from functools import reduce
l = [1, 17, 1]
result = reduce(int.__or__, l)
Upvotes: 0
Reputation: 119
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
).
Upvotes: 3
Reputation: 3838
This works for numpy reduce:
>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
Upvotes: 13
Reputation: 250891
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
Upvotes: 32