Python by Swaroop C H - HTML preview

PLEASE NOTE: This is an HTML preview only and some elements such as links or page numbers may be incorrect.
Download the book in PDF, ePub, Kindle for a complete version.

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, thelambda 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 aprint statement cannot be used inside a lambda form, only expressions.