Table of Contents

Python - lambda functions

About

Language - Lambda function in Python.

See Python - (Function|Procedure|definition)

Syntax

The expression below yields a function object.

lambda arguments: expression 

The unnamed object behaves like a function object defined with

def name(arguments):
    return expression

lambda generates a function and returns it, while def generates a function and assigns it to a name.

Type

addSLambda = lambda x: x + 's'
print type(addSLambda)
print addSLambda
print addSLambda(nico)
<type 'function'>
<function <lambda> at 0xb0ef96bc>
nicos

Argument

Lambda expressions can be used to generate functions that take in zero or more parameters.

The syntax for lambda allows for multiple ways to define the same function.

For example:

lambda x: x[0] + x[1] 
#or
lambda (x0, x1): x0 + x1
lambda x, y: (x[0] + y[0], x[1] + y[1])
lambda (x0, x1), (y0, y1): (x0 + y0, x1 + y1)

The result of applying either of these functions to tuples (1, 2) and (3, 4) would be the tuple (4, 6).

Full Example

# One-parameter function
a1 = lambda x: x[0] + x[1]
a2 = lambda (x0, x1): x0 + x1
print 'a1( (3,4) ) = {0}'.format( a1( (3,4) ) )
print 'a2( (3,4) ) = {0}'.format( a2( (3,4) ) )

# Two-parameter function
b1 = lambda x, y: (x[0] + y[0], x[1] + y[1])
b2 = lambda (x0, x1), (y0, y1): (x0 + y0, x1 + y1)
print 'b1( (1,2), (3,4) ) = {0}'.format( b1( (1,2), (3,4) ) )
print 'b2( (1,2), (3,4) ) = {0}'.format( b2( (1,2), (3,4) ) )
a1( (3,4) ) = 7
a2( (3,4) ) = 7

b1( (1,2), (3,4) ) = (4, 6)
b2( (1,2), (3,4) ) = (4, 6)

Restriction

single logical line

Lambda expressions consist of a single expression statement and cannot contain other simple statements. In short, this means that the lambda expression needs to evaluate to a value and exist on a single logical line. If more complex logic is necessary, use def in place of lambda.

evaluation to a value

Expression statements evaluate to a value (sometimes that value is None). Lambda expressions automatically return the value of their expression statement. In fact, a return statement in a lambda would raise a SyntaxError.

Statement not allowed

The following Python keywords refer to simple statements that cannot be used in a lambda expression:

Also, note that assignment statements (=) and augmented assignment statements (e.g. +=) cannot be used either.

Example

Sum

Sum of two arguments, a and b.

add = lambda a, b: a + b
print add(1,2)

If

If in Lambda is a ternary expression

lambda (x,y): x if y is None else y

Documentation / Reference