Anonymous functions in python are declared without the name and the lambda keyword is used to define these functions.
Lambda Function Syntax :
lambda arguments : expression
Lambda functions can take any number of arguments but can only have one expression. The expression is evaluated and returned. Lambda function can be used wherever function objects are required.
Why use the lambda function?
It is used when we want to use the function for a short period of time generally when we want to pass a function as an argument to hoc (a function that takes another function as an argument).
# lambda function def myfunc(n): return lambda a : a * n mydoubler = myfunc(5) mytripler = myfunc(6) print(mydoubler(11)) print(mytripler(11)) Output: 55 66
We can use it with different functions as per our needs some of the examples are listed below.
x = lambda a: a * 10 print(x(5)) Output: 50
Lambda function with filter:
# filter() with lambda() li = [7, 9, 24, 98, 56, 68, 75] final_list = list(filter(lambda x: (x%2 == 0) , li)) print(final_list) Output : [24, 98, 56, 68]
Here filter function takes the lambda function and list as an argument and returns even numbers from the list.
Lambda functions with a list comprehension.
# lambda with lists list = [lambda x=x: x*5 for x in range(1, 5)] for data in list: print(data()) Output: 5 10 15 20
Lambda with map:
#lambda with map li = [6, 9, 27] list = list(map(lambda x: x/3, li)) print(list) Output: [2.0, 3.0, 9.0]
Difference between lambda function and defined function:
#difference between defined and lambda def square(x): return x*x lambda_square = lambda x:x*x #print def print(square(7)) # print lambda print(lambda_square(7)) Output: 49 49
With defined function: while using def for the given example, we first defined function and then passed value to it and after execution, we have returned the results.
With lambda function: when using lambda we do not need to return the results. also, it can be used inside other functions.
How to write lambda in multiple lines:
for that, we need to add \ at end of the line known as the continuation character.
#lambda in multiple lines func = lambda a, b: \ b - a if a <= b else \ a * b print(func(10, 2)) Output: 20
But it is not preferred by the python style guide so it is always better to use lambda for single-line expression. which enhances the readability for larger expressions.
Thanks for reading.