Using lambda inside a function

  • A+
Category:Languages

I'm learning about lambda functions in python through tutorials online. I understand how it works but I came across an example that puzzles me (on this page https://www.w3schools.com/python/python_lambda.asp):

def myfunc(n):     return lambda a : a * n  mydoubler = myfunc(2) print(mydoubler(11)) 

I don't understand how "mydoubler" function works here. How does it take 11 as an argument when we didn't define it before. Thank you.

 


mydoubler is what myfunc(2) returns. It returns a lambda that accepts a single argument, a.

When you call on a function like this: myfunction(this_argument), it is going to resolve to what is returned in that spot. So this is effectively the same as writing mydoubler = lambda a : a * 2

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: