user3293692
user3293692

Reputation: 617

Bitwise-OR the elements of a list in python using lambda

Can I use the lambda function this way to bitwise-OR all the elements in the list?

lst = [1, 1, 1]
f = lambda x: x | b for b in lst

When I do this I get a SyntaxError.

Upvotes: 4

Views: 2202

Answers (1)

tzaman
tzaman

Reputation: 47840

You want reduce:

f = reduce(lambda x, y: x | y, lst)

reduce accepts a binary function and an iterable, and applies the operator between all elements starting from the first pair. Note: in Python 3 it moves to the functools module.

You can also use the or_ function from the operator module instead of writing the lambda yourself:

from operator import or_
f = reduce(or_, lst)

Upvotes: 15

Related Questions