4

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?

3
  • Why are you using a lambda here? A lambda is a function, so you're returning a function from your function. Commented Jul 22, 2016 at 20:32
  • 1
    @MorganThrapp It's functions all the way down! Commented Jul 22, 2016 at 20:33
  • @MorganThrapp Just seeing what I can and cannot do with lambdas in order to fully understand them and their behaviors. Commented Jul 22, 2016 at 20:38

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, this worked! I will accept your answer when the time restriction expires.
For future reference: This is not how lambda expressions are supposed to be used. In this specific case, you are wrapping your functionality in two redundant function calls. Either omit the lambda completely, or directly assign the lambda function to the variable sum_double.
@MichaelHoff totally agree. I never objected to the use, since the OP did state he was experimenting with lambdas and, while experimenting, you're generally free to try any wacky thing.
@Jim: I thought so. I just wanted to make sure that this issue is clear when some beginner comes across this question :)
2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.