4

I am having difficulty in understanding the lambda function syntax in python. In particular, I don't understand why the following code shouldn't work:

def f(x):
    return lambda x:x**2

f(2)

The output that I expect is 4 but the actual output looks like this:

<function __main__.<lambda>>

What is going on? Thanks in advance

1
  • 1
    It's a function that returns a function. So you need to call what is returned by f(2). If your looking for currying use functools.partial. Commented Jul 4, 2015 at 6:24

5 Answers 5

12

You need to call the lambda using ():

In [1]: def f(x):
   ...:     return (lambda n:n**2)(x)
   ...: 

In [2]: f(3)
Out[2]: 9

Or assign the lambda to a var:

In [3]: f=lambda x:x**2

In [4]: f(4)
Out[4]: 16
Sign up to request clarification or add additional context in comments.

Comments

2

f(2) returns the lambda. That is what <function __main__.<lambda>> is. Note that the x inside the scope of the lambda is not the same x that is passed in as the argument to f. So you could have defined your function with no arguments and it would have the same result.

To call the lambda, you can do f()(2).

Comments

1

You need to call the lambda function to get the result. Not sure what you are doing with that though.

In your case -

f(2)(2)
>>> 4

If you just want f to refer to the lambda function, then do -

f = lambda x:x**2
f(2)
>>>> 4

Do not return it from a function.

1 Comment

Do not return it from a function. - Why?
1

You are doing it wrong.
Your f function returns a lambda function, which needs to be called.
So to make it work -

>>> f(0)(2)
      ^ This can be anything
4

Try something like this -

>>> f = lambda x:x**2
>>> f(2) 
4

Comments

0

Using the parameter with '()' outside in the function should return the value.

def my_color(x): return (lambda j: 100 if j== 0 else 200)(x)

output: my_color(0) => 100

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.