Python Lambda Function
The Lambda function can be defined as a function without a name. It is anonymous. It provides an easy and quick way to define small functions in Python. A lambda function can take any number of parameters but only have one expression. The single expression is evaluated and returned and can be used anywhere.
While you normally define a function with the keyword def and a name, you can use the lambda keyword to define anonymous functions without a name. An anonymous function is variably called a lambda function.
What are Python Lambda Functions
Syntax to create a Lambda function.
Normally you create a function like this.
It has arguments and an expression. Initially, the arguments are defined, followed by a colon ":". Like this
lambdafunction = lambda num:num*num print(lambdafunction(2))
Here, num is the argument, and num*num is the expression. This lambda function returns the square of a number. The function's object is returned using lambda.
Mostly, Lambda function is used in combination with the map() and filter() functions. Like this
new_list = list(filter(lambda x:x%3==0, [1,2,3,4,5,6,7,8,9])) print(new_list)
This code returns all the elements from a list that are divisible by 3.
Lambda functions with filter()
The filter() function takes a list and a function as an input. Then it passes all the elements to the function and returns the elements for which the function becomes True.
new_list = list(map(lambda x:x*x, [1,3,5,7,9])) print(new_list)
This code returns the square of elements given in a list.
Lambda functions with map()
The map() function a list and a function as an input. The function parameter is called with all elements in the list and returns a new list containing elements returned from each element in the original list.
Here is an example of the map() function with the lambda function to get the squared value of each integer in the list.
demo_list = [1, 3, 5, 7] sq_list = list(map(lambda x: x ** 2 , demo_list )) print(sq_list )