I'd recommend
lambda x: 1 if x > 100 else (2 if x > 50 else 3)
for readability because explicit is better than implicit.
Indeed, due to evaluation from left to right, the ternary operator is right associative as the following code demonstrates
def f(a, b):
return 1 if a else 2 if b else 3
def left(a, b):
return (1 if a else 2) if b else 3
def right(a, b):
return 1 if a else (2 if b else 3)
tpl = "{:^8}{:^8}{:^6}{:^6}{:^6}"
print(tpl.format('a', 'b', 'f', 'left', 'right'))
for (a, b) in [(False, False),(False, True),(True, False),(True, True)]:
print(tpl.format(repr(a), repr(b), f(a,b), left(a,b), right(a,b)))
""" my output ->
a b f left right
False False 3 3 3
False True 2 2 2
True False 1 3 1
True True 1 1 1
"""
The ternary expression always gives the same result as the expression where everything after the first else is parenthesized.
When the conditions are (x>100) and (x>50), the case True, False can never happen, so the three expressions give the same result. Nevertheless, explicit is better than implicit!
lambda x: 1 if x > 100 else (2 if x > 50 else 3)for readability because explicit is better than implicit.elif?