3

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!

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

1 Comment

instead of a for loop, just say: l = [op(a,b) for op in ops]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.