Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does returning this lambda expression result in a string?

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?

like image 869
pianoisland Avatar asked Sep 13 '25 10:09

pianoisland


2 Answers

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
like image 193
Dimitris Fasarakis Hilliard Avatar answered Sep 14 '25 23:09

Dimitris Fasarakis Hilliard


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.

like image 32
Michael Hoff Avatar answered Sep 14 '25 23:09

Michael Hoff