Skip to content
Advertisement

Why can’t I assign lambda to the variable using ternary operator

When I assign anonymous function to the variable using ternary operator with the true condition, I can call the variable as a normal function.

>>> a = lambda x, y: x + y if True else lambda x, y: x * y
>>> a(1, 2)
3

But when the condition is false and the function to be assigned is after the word else, I get something like this. I have no idea what mechanisms stand behind such a weird behaviour. Is there any syntax nuances? Or any possibility to use ternary operator in cases like this one?

>>> a = lambda x, y: x + y if False else lambda x, y: x * y
>>> a(1, 2)
<function <lambda>.<locals>.<lambda> at 0x10916aee0>

Advertisement

Answer

You need to use parentheses to indicate your meaning.

You mean

(lambda x, y: x + y) if True
else (lambda x, y: x * y)

but you have

lambda x, y:
    (x + y if True
     else lambda x, y: x * y)

The ... if ... else ... operator has higher precedence than lambda. See https://docs.python.org/3/reference/expressions.html#operator-precedence.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement