Search code examples
pythonpython-3.xlogical-operators

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!


Solution

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