Python Forum
Using a lambda function within another function
Thread Rating:
  • 2 Vote(s) - 2 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using a lambda function within another function
#8
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

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 * 16
and 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

Reply


Messages In This Thread
RE: Using a lambda function within another function - by buran - Jan-08-2019, 01:22 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  The function of double underscore back and front in a class function name? Pedroski55 9 940 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  Add two resultant fields from python lambda function klllmmm 4 1,052 Jun-06-2023, 05:11 PM
Last Post: rajeshgk
  Exit function from nested function based on user input Turtle 5 3,115 Oct-10-2021, 12:55 AM
Last Post: Turtle
Question Stopping a parent function from a nested function? wallgraffiti 1 3,799 May-02-2021, 12:21 PM
Last Post: Gribouillis
  Writing a lambda function that sorts dictionary GJG 1 2,083 Mar-09-2021, 06:44 PM
Last Post: buran
Question exiting the outer function from the inner function banidjamali 3 3,722 Feb-27-2021, 09:47 AM
Last Post: banidjamali
  Passing argument from top-level function to embedded function JaneTan 2 2,345 Oct-15-2020, 03:50 PM
Last Post: deanhystad
  use NULL as function parameter which is a pointer function? oyster 0 2,585 Jul-11-2020, 09:02 AM
Last Post: oyster
  How to use function result in another function Ayckinn 4 2,964 Jun-16-2020, 04:50 PM
Last Post: Ayckinn
  translating lambda in function fabs 1 2,225 Apr-28-2020, 05:18 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020