Reputation: 15
I'm a noob of Python. These are my variables:
>>> y=1
>>> i=5
I use the lambda function:
>>> (lambda y: y*i)(i)
>>> 25
Why the output is 25 if y=1 and i=5???????
If I use numbers:
>>> (lambda y: 1*i)(i)
>>> 5
Is this normal? Why the y is 5 in the first case, and 1 in the other case?
Upvotes: 0
Views: 426
Reputation: 9657
These are actually working in correct manner. Your first lambda expressions is similar to:
def f(y):
return y * i
As you can see y
is the argument of the function. And it is returning the argument
* i
(whatever i
's value is).
So (lambda y: y*i)(i)
is like calling f(i)
. Now you have already set i
's value as 5. So it's basically f(5)
and returning you the value (5 * 5) -> 25.
The second expression is similar to:
def g(y):
return 1 * y
You are passing i
in g()
. i
's value is 5, So it's like calling g(5)
and it's returning you the value (1 * 5) -> 5 .
Upvotes: 2
Reputation: 799570
You've passed i
as the first argument. This means that y
in the lambda is bound to the value in i
. And then you multiply y
by i
. This results in 5 * 5, or 25.
Upvotes: 0