Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I loop through logical operators in python?

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!

like image 666
B Furtado Avatar asked Mar 26 '26 04:03

B Furtado


1 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.

like image 110
stfwn Avatar answered Mar 27 '26 18:03

stfwn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!