I am a c++ guy, learning the lambda function in python and wanna know it inside out. did some seraches before posting here. anyway, this piece of code came up to me.
<1> i dont quite understand the purpose of lambda function here. r we trying to get a function template? If so, why dont we just set up 2 parameters in the function input?
<2> also, make_incrementor(42), at this moment is equivalent to return x+42, and x is the 0,1 in f(0) and f(1)?
<3> for f(0), does it not have the same effect as >>>f = make_incrementor(42)? for f(0), what are the values for x and n respectively?
any commments are welcome! thanks.
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
make_incrementorreturns a lambda, which is a function. It can be used in cases where you need a function, such as in themapfunction. Consider this:map(f, range(0,10))will return you a list of numbers from42to51. You need a function for map that takes only 1 parameter.lambdaexpression simply creates a new function object.f = lamba x: x + nanddef f(x): return x + nproduce identical function objects bound tof.fis a function such asf(x) = x+n, n being the parameter give tomake_incrementor, i.e. 42, x being the parameter to f. sof = make_incrementor(42)gives youf(x) = x + 42, and thenf(0) = 0 + 42