'lambda: confused about parameter transmission
I come from the SQL world, and I am a newbie to this. I found on w3shools.com similar code:
def myfunc(n, m):
return lambda a : a * n * m
mydoubler = myfunc(2, 6)
print(mydoubler(15))
I cannot figure out how the a parameter, which I asssume is "15" in the call, is made available to the lambda. I searched and I could not find a description of the logical and programmatic paradigm.
Solution 1:[1]
lambda function is an anonymous function, this mean that a lambda expression is a function by itself but is inline. here, you created a function that will return a lambda expression that calculates the products of a and n and m so the returned value will be that. we know that when we return a function, we can store what we returned in a variable, in our case, we returned a lambda function so you need to enter the a value. if it is not clear, ask me
Solution 2:[2]
Lambda function is a function, but without a name. The only difference is, ho definition looks like. Your code snipped could be translated to:
def myfunc(n, m):
def some_func(a):
return a * n * m
return some_func
mydoubler = myfunc(2, 6)
print(mydoubler(15))
And the result would be the same. From the official Python docs Lambda Expressions:
Like nested function definitions, lambda functions can reference variables from the containing scope
Because of that, values of n and m are available for the function. Value of a is passed when you are executing mydoubler.
Solution 3:[3]
this is a detailed answer:
first of all, you created the function myfunc that requires 2 arguments "n" and "m". then you will return a lambda function that takes an argument "a" and returns the product of "a","n" and "m". then you declared a variable mydoubler whose value is the returned value of myfunc which is that lambda. imagine that mydoubler = lambda a: a * 2 * 6. and finally you printed the returned value of mydoubler which is a function and the argument a is 15. if you didnt understand the lambda format for mydoubler, here is it but as a normal function: def mydoubler(a): return a * 2 * 6 dont forget, 2 is the value of n and 6 is the value of m
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zakaria Ayadi |
| Solution 2 | w8eight |
| Solution 3 | Zakaria Ayadi |
