vampiire
vampiire

Reputation: 1230

python: condense conditional OR that check several variables equal to a common value

Say I want to condense the following line of code:

if a == 10 or b == 10 or sum == 10 or diff == 10:
    # do something

Is there a way to condense all of these ors to point to a single value?

Something like:

if (a or b or sum or diff) == 10:
    # do something

Upvotes: 0

Views: 102

Answers (3)

Giannis Spiliopoulos
Giannis Spiliopoulos

Reputation: 2698

Flip it around

if 10 in {a, b, sum, diff} should work

To generalize for more values use this:

if {val1, val2, val3} & {a, b, sum, diff}

Upvotes: 3

linusg
linusg

Reputation: 6439

It's not much shorter, but I'd use the built-in any():

any(val == x for val in (a, b, c))

In your case:

if any(val == 10 for val in (a, b, sum, diff)):
    # do something

Hope this helps!

Upvotes: 2

Prune
Prune

Reputation: 77900

if 10 in [a, b, sum, diff]:

However, note that this works only for a single common value. If you have two values to compare against four different variables, you don't get the "distributive law" so easily implemented.

Upvotes: 3

Related Questions