Search code examples
pythonnumpyif-statementcomparison-operatorsmultiple-conditions

Is there a way to combine memberwise comparison within an if-statement in python?


I want to check multiple conditions in an if-statement

if a:
    # do something

a in this case is true for multiple cases a==1, a==2, a==3

instead of writing

if a == 1 or a == 2 or a == 3:
    # do something

I am trying something like this

if a == condition for condition in [1, 2, 3]:
    # do something

Solution

  • Just to add to other answers, your best bet would definately be this logic:

    if a in set([1, 2, 3]):
        #do something
    

    or even better

     if a in {1, 2, 3}:
        #do something
    

    The thing I want to underline here is the fact that you should use a set for that kind of situation. Lookups will be more efficient.

    Also, python documentation recommend that.

    Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference