1

I finally understood lambdas! or so I thought

why does this not work:

Example 1:

for x in range(18, 101):
    print("Man's age: ", x, "Women's age: ", lambda x:x//2+9(x))

yet this does:

Example 2:

for x in range(18, 101):
    print("Man's age: ", x, "Women's age: ", (lambda x:x//2+9)(x))

does this mean putting a lambda on a parenthesis is the equivalent of calling it? and putting another open/close parenthesis next to it means it is it's arguments?

4
  • why do you think first would work? Commented Sep 23, 2015 at 4:47
  • @AnandSKumar I didn't know. I just got the lambda concept down man. but yeah I get it now. the parenthesis calls it. and the parenthesis next to it will be treated as it's arguments Commented Sep 23, 2015 at 4:51
  • 2
    No, the first paranthesis tells exactly where the lambda starts and ends, the (x) calls it and x is the parameter. In the first case without parameter, how would python know you didn't mean to call 9 as a function? 9(x) ? Commented Sep 23, 2015 at 4:53
  • ok gotcha. so that's why. ok I got it now. Commented Sep 23, 2015 at 4:58

2 Answers 2

3

In your first example, you are printing a lambda function definition

if the same if you assign it to a variable and try to print it.

v  = lambda x:x//2+9(x)
print v
>>function <lambda> at 0x10c32aaa0

If you want to execute it, you need to do v(x)

But, you will get an error because 9(x) statement, is trying to call a function using an int.

The proper way to use it

v  = lambda x:x//2+9
print v(2)
>>10
Sign up to request clarification or add additional context in comments.

Comments

1

Lambda defines the function but doesn't actually call it. It's the difference of just "f" and "f(x)". A clearer solution would look like:

func = lambda x: x//2+9

for x in range(18, 101):
    print("Man's age: ", x, "Women's age: ", func(x))

1 Comment

but doing so would defeat the use of lambda as an "anonymous" function yeah? it would make a clearer solution and personally I prefer your suggestion. I was just wondering why it didn't work and why the other one did

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.