In this tutorial, we will discuss Anonymous functions in Python. In Python, anonymous function is also known as lambda function.
Table of Contents
- Anonymous(Lambda) Function
- Syntax of Anonymous Function in python
- Python lambda function Example
- Example of filter() with lambda function
- Example of map() with lambda function
Python Anonymous(Lambda) Function
An anonymous function in Python is a function without name.
A function in Python is defined using def
keyword. In Python, anonymous/lambda function is defined using lambda
keyword.
Syntax of Anonymous Function in python
In Python a lambda function has following syntax:
lambda <arguments>: expression
Anonymous function allows multiple arguments but only one expression, the expression is evaluated based on the passed arguments and the result of the expression is returned.
Python lambda function Example
In the following example we are using a lambda function that returns the square of a given number.
my_square = lambda num: num * num n = 4 # Output: Square of number 4 is: 16 print("Square of number", n, "is: ",my_square(n))
Output:
In the above example, lambda num: num * num
is the lambda function that returns the square of a given argument. Here num
is the argument and num * num
is the expression.
The lambda function doesn’t have any name, the result of the lambda function is assigned to an identifier my_square
.
Lambda function lambda num: num * num
is equivalent to the following user-defined function:
def my_square(num): return num * num
Example of filter() with lambda function
The filter() function accepts two arguments: a function and a list.
The filter() function returns a new list with all those elements of the input list that meet the function condition or in other words filter() returns those elements for which the function evaluates to true.
Here we are using filter() with a lambda function to filter out the odd numbers from a given list of numbers.
# 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)
Output:
Example of map() with lambda function
Similar to filter() function, the map() function takes a function and a list as arguments.
The map() function returns a new list with the items that are returned by the function for each of the elements of input list.
Here we are using map() and a lambda function to return the square of each element of the given list.
# 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)
Output:
As you can see in the output that the list has the square of the each element of the input list.
Leave a Reply