<< Back to man.ChinaUnix.net

A Byte of Python

Lambda Forms

A lambda statement is used to create new function objects and then return them at runtime.

Using Lambda Forms

Example 15.2. Using Lambda Forms

				
#!/usr/bin/python
# Filename: lambda.py

def make_repeater(n):
	return lambda s: s * n

twice = make_repeater(2)

print twice('word')
print twice(5)
				
				

Output

				
$ python lambda.py
wordword
10
				
				

How It Works

Here, we use a function make_repeater to create new function objects at runtime and return it. A lambda statement is used to create the function object. Essentially, the lambda takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function. Note that even a print statement cannot be used inside a lambda form, only expressions.