python, basic lambda function -


i c++ guy, learning lambda function in python , wanna know inside out. did seraches before posting here. anyway, piece of code came me.

<1> dont quite understand purpose of lambda function here. r trying function template? if so, why dont set 2 parameters in function input?

<2> also, make_incrementor(42), @ moment equivalent return x+42, , x 0,1 in f(0) , f(1)?

<3> f(0), not have same effect >>>f = make_incrementor(42)? f(0), values x , n respectively?

any commments welcome! thanks.

>>> def make_incrementor(n): ... return lambda x: x + n ... >>> f = make_incrementor(42) >>> f(0) 42 >>> f(1) 43 

  1. yes, similar c++ int template. however, instead of @ compile time (yes, python (at least cpython) "compiled"), function created @ run time. why lambda used in specific case unclear, demonstration functions can returned other functions rather practical use. sometimes, however, statements may necessary if need function taking specified number of arguments (e.g. map, function must take same number of arguments number of iterables given map) behaviour of function should depend on other arguments.

  2. make_incrementor returns function adds n (here, 42) x passed function. in case x values tried 0 , `1``

  3. f = make_incrementor(42) sets f function returns x + 42. f(0), however, returns 0 + 42, 42 - returned types , values both different, different expressions don't have same effect.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -