brokenpc
brokenpc

Reputation: 1

A question on interpreting function and lambda function in Python

I am having a hard time with a practice problem involving function and lambda using Python. I wonder if you could help me explain how this function works:

The problem is: What is the expected output of the following code:

v = [1, 2, 3]

def g(a,b,m):
    return m(a,b)

print(g(1, 1, lambda x,y: v[x:y+1]))

I understand that the lambda part is equivalent to v[1:2] which is slicing v and returns [2, 3], but how do I interpret g(1, 1, [2,3])?

Thank you for your help.

Upvotes: 0

Views: 52

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

A lambda is just a self-contained function inside a single expression. Internally, there's almost no actual difference between functions and lambdas other than the syntax for writing them.

The thing you might not be seeing is that you can pass a function like any regular variable (so the third argument of g() is a function/lambda). So, in your case, you're creating a lambda:

lambda x,y: v[x:y+1]

and passing it as the third argument to g(). Inside g(), the third argument gets called with the first and second arguments. So the lambda doesn't get actually called until inside the function - defining it does not automatically execute it.

g(1, 1, [2, 3]) would fail, because [2, 3] is not callable (consider: [2, 3](a, b) doesn't make sense).


The following code would be functionally identical to what you have (replacing the lambda with a normal function):

v = [1, 2, 3]
def lam(x, y):
    return v[x:y+1]

def g(a,b,m):
    return m(a,b)

print(g(1, 1, lam))

Upvotes: 1

Related Questions