Reputation: 5470
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
Upvotes: 4
Views: 8011
Reputation: 1
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
Upvotes: 0
Reputation: 1238
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)
.
Upvotes: 2
Reputation: 5488
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
Upvotes: 1
Reputation: 90979
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.
Upvotes: 1
Reputation: 34037
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
Upvotes: 12