Difference between revisions of "Lambda function"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(created)
 
m ({{Sufficient-class}})
Line 1: Line 1:
 +
{{Sufficient-class}}
 
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. Use a lambda function if its body is a simple expression.  
 
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. Use a lambda function if its body is a simple expression.  
  

Revision as of 12:53, 4 June 2014

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 def statement. Use a lambda function if its body is a simple expression.

Examples

>>> def call_f(f):
...     return f()
... 
>>> call_f(lambda: 3)
3

You can bind a variable name to a lambda function if you want to refer to it in the future:

>>> even = lambda x: x % 2 == 0
>>> even(40)
True
>>> even(5)
False

You can also call lambda functions like regular functions:

>>> (lambda x: x % 2 == 0)(40)
True