Can I loop through logical operators in python?

Viewed 272

In order to avoid repetition, I would like to do something like this:

a, b = True, False
l = list()
for op in [and, or, xor]:
    l.append(a op b)

I tried import operator and also itertools, but they do not contain logical operators, just math and some other ones.

I could not find any previous answer that was helpful!

2 Answers

Your example can be implemented using the operator module.

from operator import and_, or_, xor

ops = [and_, or_, xor]
l = [op(a,b) for op in ops]

These are bitwise operators, but for booleans -- which are represented in only one bit -- they double as logical operators.

or and and can't really be replicated by functions because they short-circuit; but if you don't care about that you can write lambda functions, e.g. lamba x, y: x and y. For xor on booleans you could use operator.ne.

ops = [(lambda x,y: x and y), (lambda x,y: x or y), operator.ne]
l = [op(a,b) for op in ops]

The list comprehension was suggested by Adrian W in the comments.

Update: Use stfwn's answer. It's better.

Related