Lambda functions
In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def
keyword, in Python anonymous functions are defined using the lambda
keyword.
Syntax: lambda arguments: expression
Lambda functions can have any number of arguments but only one expression, which is evaluated and returned. Lambda functions can be used wherever function objects are required.
Example
double = lambda x: x * 2
print(double(5)) # Output: 10
In the above program, lambda x: x * 2
is the lambda function. Here x
is the argument and x * 2
is the expression that gets evaluated and returned. It returns a function object which is assigned to the identifier double
. We can now call it as a normal function.
Use of Lambda functions
Lambda functions are used when a nameless function is required for a short period of time. They are generally used as an argument to a higher-order function (a function that takes in other functions as arguments), often along with built-in functions like filter()
, map()
etc.
Example using filter()
The filter()
function in Python takes in a function and a list as arguments. The function is called with all the items in the list and a new list is returned which contains items for which the function evaluats to True.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x % 2 == 0) , my_list))
print(new_list) # Output: [4, 6, 8, 12]
Example using map()
The map()
function in Python takes in a function and a list. The function is called with all the items in the list and a new list is returned which contains items returned by that function for each item.
# Program to double each item in a list using map()
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list) # Output: [2, 10, 8, 12, 16, 22, 6, 24]