+ 1

lambda

Hi, why this script: sum = lambda x,y,z: x+2*y+(1/4*z) (1,2,3) print(sum) have this output: <function <lambda> at 0x7f78051e62f0> ? And what i need to read about it? P.S.: if you are a newbie like me, you need to add () to this script: sum = (lambda x,y,z: x+2*y+(1/4*z)) (1,2,3) print(sum) and output will be right: 5.75

30th Mar 2018, 8:39 AM
Adam Kandur
Adam Kandur - avatar
2 Answers
+ 4
By writing: sum = (lambda x,y,z: x+2*y+(1/4*z)) (1,2,3) you will store in 'sum' the result of the lambda function call with (1,2,3) as arguments... That's not really usefull, and if you know what are the arguments value at code writing time, you simpler could write: sum = 1+2*2+(1/4*3) On the other hand, by writing: sum = lambda x,y,z: x+2*y+(1/4*z) ... you store the function object in 'sum', and you could call it later with different arguments: print(sum(1,2,3)) print(sum(4,5,6)) Anyway, by "just" storing a lambda function inside a variable, you "just" do quite the same thing as defining a "normal" (named) function: def sum(x,y,z): return x+2*y+(1/4*z) The "real" need to store a lambda function inside a function instead of "defining" it as a "named" function, is to define it onelined and almost to define a list or a dict of functions: utils = { "sum" : lambda x,y : x+y, "diff" : lambda x,y : x-y, "mult" : lambda x,y : x*y, "div" : lambda x,y : x/y, } print(utils["sum"](30,12)) ... however, you could do same by (more lines) writing: def sum(x,y): return x+y def diff(x,y): return x-y def mult(x,y): return x*y def div(x,y): return x/y utils = { "sum" : sum, "diff" : diff, "mult" : mult, "div" : div, }
30th Mar 2018, 11:50 AM
visph
visph - avatar
+ 6
Exactly what you found out - you have to be precise with your commands. print(sum) outputs the datatype and print(sum()) actually calls the function and outputs its result.
30th Mar 2018, 9:27 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar