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?
0and""are also false-y, you should probably haveval1 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.val1is evaluated as False - e.g. 0, empty string, empty containers...val1 if val1 else val2is indeed exactly equivalent toval1 or val2. I'd consider theorversion 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 isval1 and val1.val2as a shorthand forval1.val2 if val1 else None.val1 or val2is not that common, but rather explicit if else checks are more common