Bitwise operations between items in a list

I have a list of bitwise elements, for example. [1,1,1], and I want to execute a bitwise OR between each item in the list. For example,

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 a loop? Numpy bitwise_or only works on 2 arrays. There are bitwise and or | which works on every element like sum or np.mean? Thank you

+8
source share
3 answers

This works for numpy reduce :

>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
+8
source

You can use reducewith operator.ior:

>>> from operator import ior
>>> lst = [1, 17, 1]
>>> reduce(ior, lst)
17

@DSM , numpy :

>>> import numpy as np
>>> arr = np.array(lst)
>>> np.bitwise_or.reduce(arr)
17
+19

Without importing anything, nor numpyany operator.ior, as suggested in the other answers:

a = [1,17,1]
reduce(lambda x,y: x | y, a)

Edit: However, when I was comparing various options, it 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 reduceit was eliminated (although it can still be imported from functools).

0
source

All Articles