We’ll talk about Python’s anonymous functions in this lesson. Lambda function and anonymous function are both terms used in Python.
Python Anonymous(Lambda) Function
In Python, a nameless function is known as an anonymous function.
The Python def keyword is used to define a function. The lambda keyword in Python is used to define anonymous/lambda functions.
Syntax of Anonymous Function in python
A lambda function in Python has the following syntax:
lambda <arguments>: expression
Multiple parameters may be supplied, but only one expression may be used with an anonymous function. The expression’s outcome is returned once it has been evaluated using the arguments that have been passed.
Python lambda function Example
The lambda function in the example that follows returns the square of a specified integer.
my_square = lambda num: num * num n = 4 # Output: Square of number 4 is: 16 print("Square of number", n, "is: ",my_square(n))
In the previous illustration, lambda num: The lambda function that returns the square of an argument is num * num. The argument in this case is num, and the expression is
num * num .
The output of the lambda function is given the identifier my square, while the lambda function itself has no name.
lambda num: num * num is equivalent to the user-defined function that follows:
def my_square(num): return num * num
Example of filter() with lambda function
A function and a list are both acceptable parameters for the filter() function.
The filter() method provides a new list containing all of the input list’s items that satisfy the function’s requirement, or, to put it another way, returns all of the elements for which the function evaluates to true.
To remove the odd numbers from a list of integers, we are using the filter() method in conjunction with a lambda function in this case.
# Program to filter out odd numbers from a given list lis = [10, 3, 2, 11, 13, 14, 15] lis_new = list(filter(lambda num: (num%2 != 0) , lis)) # Output: [3, 11, 13, 15] print(lis_new)
Example of map() with lambda function
The map() function accepts a function and a list as inputs, just as the filter() method.
Each element of the input list is represented by an item in a new list that is returned by the map() method.
In this case, we are returning the square of each member of the supplied list using map() and a lambda function.
# Program to find out the square of each element of the list lis = [10, 9, 1, 2, 7, 11] lis_new = list(map(lambda num: num * num , lis)) # Output: [100, 81, 1, 4, 49, 121] print(lis_new)