Lambda function in another function

Question:

I’m new to Python and I’m trying to understand how this function is working:

def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

So I pass 3 to myfunc and I get 3a as a returned value. I don’t understand how value 11 which I send as an argument from mytripler function gets involved with myfunc. When I try to write the function like this I can’t get the same result:

def myfunc(n, a):
  return lambda a : a * n

print (myfunc(11, 3))

Can someone explain me?

Asked By: MCdaniel

||

Answers:

To make sure you understand it better, let’s rewrite your example and see the output at each step:

def myfunc(n):
  return lambda a : a * n

mytripler = myfunc(3)
type_of_mytripler=type(myfunc(3))
print(f'after the first call, you get {mytripler=} with {type_of_mytripler=}')

result=mytripler(11)
type_of_result=type(mytripler(11))
print(f'after the second call, you get {result=} with {type_of_result=}')

You get the following output:

after the first call, you get mytripler=<function myfunc.<locals>.<lambda> at 0x7fd196415940> with type_of_mytripler=<class 'function'>
after the second call, you get result=33 with type_of_result=<class 'int'>
33

As you can see, during the first call you actually return a lambda function. Afterward, you have to pass a new arg to your function to execute it and get a final result. You could also rewrite your example as
result=myfunc(3)(11) to achieve the same result.

To summarize, keep in mind that in Python functions are objects as well. That is, you can both pass them as arguments to other functions or return them. Obviously, you can’t get a final result out of a function itself unless you execute it using round brackets. What you effectively created is a function that returns a function.

Check the topic decorators in Python which might be a little bit complicated now but should give you a general idea about passing/returning functions as objects. This Real Python article is a good intro to this topic. For now, you might find a few paragraphs about the functions in Python most useful

Answered By: Alex.Kh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.