I am taking the w3 python tutorial and in the lambda section they give me this code
def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11))which results in 22, I understand that, what I don't understand is why the variable "a" gets the parameter of 11, that is, I understand that "n" is 2 because it is defined in the third line, but when 11 is entered ? or rather, because the 11 of the last line ends up being "a" inside lambda...
I know it is more a question of understanding the syntax than an error as such, but I would like to understand that before continuing
It is a 2-step operation. First the 2 is passed and an anonymous function (lambda) prepared to receive another parameter is returned. Then 11 is sent to it, and the anonymous function (which has an return ) returns the evaluated operation.
>>> def myfunc(n): ... return lambda a : a * n ... >>> mydoubler = myfunc(2) >>> mydoubler <function myfunc.<locals>.<lambda> at ...> # <-- devuelve una función >>> print(mydoubler(11)) 22 >>> myfunc(3)(20) 60The same function written in basic form, without lambda:
def myfunc(n): def lambda_(a): return a * n return lambda_I suggest you read something about nested functions , which is a very useful feature of the language and is the preamble for decorators .