0
b = lambda x: (lambda x: x)
print(b(88))

Why does the python code prints function instead of 88? Why is this different from the code below?

b = lambda x:c(x)

c = lambda x:x

print(b(88))
6
  • 2
    because that's the result of b(88), a function. Not sure why you expected to see 88. Commented Jan 4, 2022 at 17:43
  • To get 88 you need to do this: b(1234567)(88) (as you may notice, the first parameter is useless, because you are not using it) Commented Jan 4, 2022 at 17:49
  • Thanks Riccardo. Is it because this is a nested function, so I need to have the arguments twice? Commented Jan 4, 2022 at 17:53
  • Try this piece of code, and try to understand why you get 88: b=lambda x: (lambda x: x)(x); print(b(88)) ;) Commented Jan 4, 2022 at 17:58
  • let me try this: lambda is equivalent to define the function, in this case : def identity(x) return x. So lambda x: x is equivalent to identity. In order to call this function, I have to provide the argument, identity(88). Here (lambda x: x)(x) is equivalent to identity(x) rather than identity. So I am calling this function within b, whereas in the previous example I only defined within b not called? Am I understanding it right? Commented Jan 4, 2022 at 22:39

3 Answers 3

2
b = lambda x: (lambda x: x)

Your code is equivalent to this:

def b(x):   # <- This "x" is not used
    def anonymous(x):
        return x;
    return anonymous

So you can call it like this:

>>> b("anything")(88)
88

This code:

c = lambda x:x
b = lambda x:c(x)

is equivalent to:

def c(x):
    return x

def b(x):
    return c(x)

So if you call b(88), it will call c(88) and return the result. c(88) just returns 88.

Sign up to request clarification or add additional context in comments.

Comments

0

Functions are first class objects in python. This means that they can be treated as values. In your case, your b function is returning a function (let's call it c). Note that I got rid of the x parameter in your b function, because it's useless.

b = lambda: (lambda x: x)
c = b()

Now you can call c, since it's a function (c needs a parameter, x):

print(c(88)) # this prints 88

Comments

0

Thank you guys for the help. I think I am getting a hang of it:

b = lambda x: (lambda x: x)

is equivalent to:

def lambda_1(x):
    def lambda_2(x):
        return x
    return lambda_2

b = lambda_1

whereas

b = lambda x: (lambda x: x)(x)

is equivalent to:

def lambda_1(x):
    def lambda_2(x):
        return x
    return lambda_2(x)
b = lambda_1

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.