I just stumbled upon some unexpected behavior in Python in the code snippet below
b = False
func_1 = lambda x,y:set([x]) == y if b else lambda x,y: x in y
func_2 = None
if not b:
func_2 = lambda x,y : x in y
else:
func_2 = lambda x,y:set([x]) == y
print(func_1("Hello", set(["Hello", "World"])))
print(func_2("Hello", set(["Hello", "World"])))
Output signal
<function <lambda>.<locals>.<lambda> at 0x7f7e5eeed048>
True
However, when adding brackets around the lambda, everything works as expected:
func_1 = (lambda x,y:set([x]) == y) if b else (lambda x,y: x in y)
Then the conclusion will be
True
True
Why do I need these brackets? I thought the initial expression is equivalent to the long if-else construct.
source
share