Python Lambda Functions
Contents
What are lambda functions in Python?
Lambda functions, also known as anonymous function are the functions without a name. As Python uses the def keyword to define the function, but to define a lambda function, we do not need to use the keyword def. A lambda function can take any number of arguments, but can only have one expression.
How to use lambda Functions in Python?
Example of Lambda Function in python
Let us be more clear with an example that shows the use of lambda function over normal function.
def square(y): return y * y sq = lambda x: x * x print("Normal Function square(): ", square(5)) print("Lambda Function sq():", sq(7))
The output of the above program is:-
Lambda Function sq(): 49
Use of Lambda Function with map()
map() function takes two arguments, viz. a function and a list. The function is called with a lambda function and a list and a new list is returned which contains all the lambda modified items returned by that function for each item.
For Example:
mylist = [2, 5, 19, 25, 34, 55] updated_list = list(map(lambda x: x * 2, mylist)) print(updated_list)
The output is:-
Use of Lambda Function with filter()
The filter() function takes a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True. Here is an example program that returns the even numbers from an input list:
mylist = [3, 10, 17, 23, 124, 450, 300, 301, 304] updatded_list = list(filter(lambda x: (x % 2 == 0), mylist)) print(updatded_list)
The output of the program is:-
Use of Lambda Function with reduce()
The reduce() function takes a function and a list as arguments. The function is called with a lambda function and a list and a new reduced result is returned. This performs a repetitive operation over the pairs of the list. This is a part of the functools module.
from functools import reduce mylist = [3, 10, 17, 23, 124, 450, 300, 301, 304] sum = reduce((lambda x, y: x + y), mylist) print("Sum = ", sum)
The output of the program is:-