I recently started learning Python 3.5.1, and am currently experimenting with lambda
expressions. I tried setting up the simple method below.
def sum_double(a, b):
return lambda a, b: a+b if a != b else (a+b)*2, a, b
All it is supposed to do is return the sum of a
and b
, and twice their sum if a
is equal to b
, but instead I get an output that looks like this.
Code:
print(sum_double(1, 2))
print(sum_double(2, 3))
print(sum_double(2, 2))
Output:
(<function sum_double.<locals>.<lambda> at 0x000001532DC0FA60>, 1, 2)
(<function sum_double.<locals>.<lambda> at 0x000001532DC0FA60>, 2, 3)
(<function sum_double.<locals>.<lambda> at 0x000001532DC0FA60>, 2, 2)
Am I doing this wrong? Why is this happening, and how would I use a lambda expression to achieve my desired functionality if that is even possible?
Well, you're not calling the lambda
function and as such the return value is a tuple of the defined lambda
function and the values of a
and b
.
Change it to call the lambda before returning while supplying the arguments to it:
return (lambda a, b: a+b if a != b else (a+b)*2)(a, b)
And it works just fine:
print(sum_double(1, 2))
3
print(sum_double(2, 2))
8
sum_double = lambda a, b: a+b if a != b else (a+b)*2
lambda
itself defines a function. A def
is not required.
In your case, a tuple consisting of the returned function, a
and b
is printed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With