I think your confusion is not with lambda, but with functions altogether. Let's look at your second snippet (fixed for the NameError) and with some additions from me
Now, what you describe as blueprint for function:
def foo(n,m): return lambda a: a * (n + m) bar = foo(n=11, m=5) print(bar(a=3))on line#4 you supply values for n and m (i.e. arguments for foo() function, not the lambda. Now bar function is effectively the same as
def bar(a): return a * 16and then you call bar(), supplying the
a
argument.Now, what you describe as blueprint for function:
def my_power(power): return lambda x: x ** power pow2 = my_power(2) # pow2 will get an argument and will raise to power of 2 pow3 = my_power(3) # pow3 will get an argument and will raise to power of 3 print(pow2(2)) # x=2 print(pow3(5)) # x=5
Output:4
125
>>>
Now there are other way to create "blueprints for function"from functools import partial def my_power(num, power): return num ** power pow2 = partial(my_power, power=2) pow3 = partial(my_power, power=3) print(pow2(2)) # num=2 print(pow3(5)) # num=5 # and you still can do print(my_power(2, 3))
Output:4
125
8
>>>
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs