if anonymous, what is a call to python lambda? -
i have lambda_expr ::= "lambda" [parameter_list]: expression
and supposed able without assigning name. constitutes call lambda function. in other words, if want use inline function, makes supposed do?
a lambda expression returns function
object, call same other function, ()
.
>>> (lambda x : x + 3)(5) 8
a more "normal"-looking function call works same way, except function object referenced name, rather directly. following demonstrate 3 different ways of accomplishing same thing: calling function returns value of argument plus three.
def foo_by_statement(x): return x + 3 foo_by_expression = lambda x: x + 3 print foo_by_statement(2) print foo_by_expression(2) print (lambda x: x + 3)(2)
the first traditional way of binding function object name, using def
statement. second equivalent binding, using direct assignment bind name result of lambda
expression. third again calling return value of lambda
expression directly without binding name first.
normally, never write code this. lambda
expressions useful generating function objects needed arguments higher-order functions. rather having define function , bind name never use again, create value , pass argument. example:
plus_three = map(lambda x: x+3, [1,2,3])
Comments
Post a Comment