Overview:
The lambda keyword in Python is used for writing lambda expressions. These lambda expressions produce anonymous functions which are also called function objects.
These anonymous functions do not have a name. The function object returned from a lambda expression is called as lambda function.
A Python lambda expression is of the following form:
lambda p1, p2…pn:<valid Python expression>
where p1, p2...pn are the parameters to the lambda expression.
e.g., The lambda expression, area = lambda radius: 3.14*pow(radius, 2) produces a function object when invoked with the parameter radius - area(3), returns the area of a circle as 28.26 units.
In Python, statements and annotations are not allowed in a lambda expression. Though a lambda function does not have a name, they can be assigned to a variable and the variable name can be used to invoke the function object.
Except for the restriction of not allowing any statements or annotations and not having a name, the lambda function is very similar to a regular function.
Example 1 - Lambda expression in Python:
This Python example uses a lambda function as a parameter to the built-in function filter to produce a new sequence. Based on the return value of the lambda function for each item in the original sequence, a new sequence is produced.
|
# Example Python program that prints only the numbers print("Multiples of five:") |
Output:
|
Multiples of five: |
Example 2 - A Python function that returns a lambda expression:
The lambda function produce() returns a lambda function for each value it receives for the parameter base. In mathematics, a function that returns another function is called a higher order function.
|
# Function that returns a lamda expression # Make squares # Two square # Three square # Make cubes # Two cube # Three cube |
Output:
|
Squares of numbers: |
Example 3 - A lambda expression using two parameters:
|
# Example Python program that finds the # Area of the rectangle1 whose length is 4 and # Area of the rectangle2 whose length is 6 and |
Output:
|
Area of the rectangle:12 |