Why output of this line (lambda x: x * 99 + x) (1 ** 5 * 5)
in Python is 500 while 'x' is not defined?
- 60
- 5
-
4But `x` *is* defined within the scope of the lambda. – 0x5453 May 03 '21 at 19:56
-
3the lambda defines x as an input parameter then acts upon it – Chris Doyle May 03 '21 at 19:56
-
2`(1**5*5)` is your `x`. See https://stackoverflow.com/questions/6476825/what-do-double-parentheses-mean-in-a-function-call-e-g-funcstuffstuff – banderlog013 May 03 '21 at 20:00
4 Answers
Here, (1 ** 5 * 5)
is passed as an argument to a lambda function.
(lambda x: x * 99 + x)(1 ** 5 * 5)
lambda takes input as x and acts upon it. If you have any other Lambda function it'll work in the same way.
(lambda x: x.upper())('test') # will print TEST
It's just like you're creating a function with arg x.
upper = (lambda x: x.upper())
upper('test') # will print TEST
upper
here is a lambda function
that takes arg x
and acts upon it
<function __main__.<lambda>(x)>
- 7,269
- 1
- 4
- 16
Your lambda expression (lambda x: x * 99 + x) (1 ** 5 * 5)
is comprised of two parts:
Declaring the function:
(lambda x: x * 99 + x)
which is equivalent to declaring the custom function as:
def func(x): return (x * 99 + x)
Calling the above function with argument as
(1 ** 5 * 5)
, which is equivalent to making the function call as:func(1 ** 5 * 5) # i.e. func(5) ## 1**5*5 => 5
Because 5 * 99 + 5
is equivalent to 500
. That's the answer you are getting.
- 40,020
- 8
- 82
- 111
let's review your code
(lambda x: x * 99 + x) (1 ** 5 * 5)
that's mean x*99+x
you'r input is (1**5*5)
which equals 5 that's mean x=5
so 5*99+5=500
- 528
- 1
- 5
- 13
Let's break this down.
A lambda is basically a function. In your case, it has one input (x
) and the return statement of x * 99 + x
. It is then called with (1 ** 5 * 5)
.
This means that (1 ** 5 * 5)
is x
.
You can now do the math:
1 ** 5 * 5
> 1 * 5
> 5
x * 99 + x
> 5 * 99 + x
> 500
- 1,312
- 1
- 5
- 24