You could use a list comprehension. Use izip
from itertools if you're using Python 2.
c = [x | y for x, y in zip(a, b)]
Alternatively, @georg pointed out in a comment that you can import the bitwise or operator and use it with map
. This is only slightly faster than the list comprehension. map
doesn't need wrapped with list()
in Python 2.
import operator
c = list(map(operator.or_, a, b))
Performance
List comprehension:
$ python -m timeit -s "a = [1, 0, 0, 1, 0, 0]; b = [0, 1, 0, 1, 0, 1]" \
> "[x | y for x, y in zip(a, b)]"
1000000 loops, best of 3: 1.41 usec per loop
Map:
$ python -m timeit -s "a = [1, 0, 0, 1, 0, 0]; b = [0, 1, 0, 1, 0, 1]; \
> from operator import or_" "list(map(or_, a, b))"
1000000 loops, best of 3: 1.31 usec per loop
NumPy
$ python -m timeit -s "import numpy; a = [1, 0, 0, 1, 0, 0]; \
> b = [0, 1, 0, 1, 0, 1]" "na = numpy.array(a); nb = numpy.array(b); na | nb"
100000 loops, best of 3: 6.07 usec per loop
NumPy (where a
and b
have already been converted to numpy arrays):
$ python -m timeit -s "import numpy; a = numpy.array([1, 0, 0, 1, 0, 0]); \
> b = numpy.array([0, 1, 0, 1, 0, 1])" "a | b"
1000000 loops, best of 3: 1.1 usec per loop
Conclusion: Unless you need NumPy for other operations, it's not worth the conversion.