Python Lambda Functions


The lambda keyword creates a small anonymous function or procedure.

It creates a function object the same way that the def keyword does, but with the following rules:

1. The lambda construct does not have a return statement.
2. The body can contain only a single expression.
3. The expression may yield a value.
4. The expression may be a conditional statement which returns a value.

Lambda may also be used to create anonymous procedures for use in GUI callbacks.

Lambda Examples

Here is a simple example of a lambda function.

g = lambda x: x**2
print g(8)

The result is: 64

Here is an example using two arguments:

g=lambda x,y: x+y
print g(2,3)

The result is: 5

A lambda function may be used inside a regular function.

def transform(n):
return lambda x: x + n
f = transform(3)
print f(4)

The result is: 7

Map function

A lambda function may be used with a map function to process a sequence of values.

g = lambda x: x**2
temp=(1, 2, 3, 4)
f = map(g, temp)
print f

The result is: [1, 4, 9, 16]

Reduce function

The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value.
The following sum a list of numbers.

reduce(lambda x,y: x+y, [47,11,42,13])

Result: 113

These statements find the maximum in a list.

f = lambda a,b: a if (a > b) else b
reduce(f, [47,11,42,102,13])

Result: 102

Calculate the sum of the numbers from 1 to 100:

reduce(lambda x, y: x+y, range(1,101))

Result: 5050

* * *

Tom Irvine

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s