https://www.ocf.berkeley.edu/~shidi/cs61a/w/api.php?action=feedcontributions&user=136.152.36.4&feedformat=atomCS 61A Wiki - User contributions [en]2024-03-29T08:12:28ZUser contributionsMediaWiki 1.22.6https://www.ocf.berkeley.edu/~shidi/cs61a/wiki/Lambda_functionLambda function2014-06-27T18:09:00Z<p>136.152.36.4: </p>
<hr />
<div>{{Sufficient-class}}<br />
A '''lambda function''' is an anonymous [[function]]; that is, it has no intrinsic name. It is a compact way to define a function inline without using the <tt>def</tt> [[Statement#Function_definition| statement]]. Use a lambda function if its body is a single [[expression]]. <br />
<br />
Lambda functions can be used wherever function objects are required.<br />
<br />
== Definition ==<br />
<syntaxhighlight lang="python"><br />
lambda args: return_expression<br />
</syntaxhighlight><br />
The lambda expression above in Python is equivalent to the function defined below. <br />
<syntaxhighlight lang="python"><br />
def <lambda>(args):<br />
return return_expression <br />
</syntaxhighlight><br />
Note that unlike with <code>def</code>, the lambda function does not automatically get bound to a name in the [[frame]] (hence its anonymity). In an [[environment diagram]], a new function object is created in the heap when the lambda expression gets evaluated.<br />
<!-- A lambda function is lexically scoped, so the new function object's parent is the current frame, the frame in which the lambda expression is evaluated, not the frame where any subsequent call expressions gets evaluated. --><br />
<br />
== Examples ==<br />
<syntaxhighlight lang="python"><br />
>>> def call_f(f):<br />
... return f()<br />
... <br />
>>> call_f(lambda: 3)<br />
3<br />
</syntaxhighlight><br />
<br />
You can bind a variable name to a lambda function if you want to refer to it in the future:<br />
<syntaxhighlight lang="python"><br />
>>> even = lambda x: x % 2 == 0<br />
>>> even(40)<br />
True<br />
>>> even(5)<br />
False<br />
</syntaxhighlight><br />
<br />
You can also call lambda functions like regular functions:<br />
<syntaxhighlight lang="python"><br />
>>> (lambda x: x % 2 == 0)(40)<br />
True<br />
</syntaxhighlight><br />
<br />
==External links==<br />
*[http://docs.python.org/3.4/reference/expressions.html#lambda| Python 3.4 language reference for lambdas]</div>136.152.36.4