1

Let's say we have two integer or string values and we would like to select the value out of those two which is not None.

val1 = None val2 = 100 

The mainstream or conventional way of doing this would be

val = val1 if val1 else val2 or val = val1 if val1 is not None else val2 

But I am unsure why is this approach not used as this yields the same output.

val = val1 or val2 

The second approach becomes specially much more useful when we have to select a non-null value out of multiple values. So it becomes simply

val = val1 or val2 or val3 or val4 

Am I missing any underlying concept here?

4
  • 6
    Note 0 and "" are also false-y, you should probably have val1 if val1 is not None else val2. As to why you'd use the conditional vs logical expression, that's going to depend on context and preference. Commented Jun 14, 2022 at 14:02
  • mainstream or conventional way of doing this would be - what makes you think so? Note the @jonrsharpe comment - both lines will yield the same result when val1 is evaluated as False - e.g. 0, empty string, empty containers... Commented Jun 14, 2022 at 14:04
  • val1 if val1 else val2 is indeed exactly equivalent to val1 or val2. I'd consider the or version to be more pythonic (it's the exact reason the operator works that way), but it's somewhat unique to Python so not everyone knows it's there. Another handy trick is val1 and val1.val2 as a shorthand for val1.val2 if val1 else None. Commented Jun 14, 2022 at 14:04
  • fantastic insight @jonrsharpe, probably that is why val1 or val2 is not that common, but rather explicit if else checks are more common Commented Jun 15, 2022 at 8:20

1 Answer 1

2

Both are wrong. What you want is something like this:

val = val1 if val1 is not None else val2 

which is correct for

val1 = 0 val2 = None 

(If both values are None, you'll have to check for that explicitly to avoid val = None, if necessary.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.