3

I have a small python script where a variable inside a lambda function (which is inside another function) does not take any value from somewhere but still the script works and I can not understand why. Below I have my code, a is the mysterious variable. I know that for some reason it works but I don't know why.

 def myfunc(n):
   return lambda a : a * n <== a variable takes value from where???

 mydoubler = myfunc(2)
 print(mydoubler(11))
Argon888
  • 71
  • 4

2 Answers2

4

You declared the variable here:

def myfunc(n):
   return lambda a : a * n

a is the name of the argument to the lambda

lambda a

This is equivalent to:

def some_name(a):
    ...

The only difference is that lambda is like a function with no name. Anonymous.

rdas
  • 20,604
  • 6
  • 33
  • 46
1

Your myfunc(n) does not return a value it returns another function that has n according to whatever you called myfunc with and will - when executed - take its parameter a and multiply it by n:

def myfunc(n):
   return lambda a : a * n 

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(type(mydoubler))  # <class 'function'> - n is set to 2
print(type(mytripler))  # <class 'function'> - n is set to 3

print(mydoubler(10)) # 20
print(mytripler(20)) # 60

You can even inspect your lambda and see what param it takes:

from inspect import signature

print(signature(mydoubler)) # (a)
print(signature(mytripler)) # (a)
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69