wnnmaw
wnnmaw

Reputation: 5524

What is the most efficient way to do multiple or comparisons if some are conditional

I have a value, val which I want to check if it is one of several values (1, 2, or 3). Normally the way I would do this is:

if val in [1,2,3]:

However, I only want to include 3 if another condition is met (test). Ungracefully put, it would be this:

if val in [1,2,3] and (test if val == 3 else True):

This is a pretty awkward comparison (isn't very readable) and I'm testing if val == 3 twice, so is there a way to do it all in one go? (i.e. more efficiently) Thanks in advance,

Upvotes: 3

Views: 89

Answers (1)

ndpu
ndpu

Reputation: 22561

if val in [1,2] or (val == 3 and test):
   # do it

More efficient than with and and clearer. With or operator expression divided into 2 parts and right part evaluated only if left is False. From python docs:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Upvotes: 6

Related Questions