In this session, we are going to discuss the following about lambda functions.
- What are lambda functions?
- Lambda syntax
- How they are use and how they are created.
- Lambda functions
A lambda functions also called an anonymous function, are functions which are defined without a name. While you would define a function with the normal ‘def keyword’ instead lambda functions are defined with the lambda keyword. They are mostly used when we need a nameless function for a short period of time.
Syntax of the lambda function
Lambda arguments: expression
You can use a lambda function anywhere a function is needed.
Here is an example of a program that uses the lambda function that squares the values of the input
squared = lambda x: x**2
print(squared(10))
OUTPUT
In the above program, lambda x: x**2 is the lambda function where x is the argument and x **2 is the expression that the compiler evaluates and returns as the results. In python, lambda functions are generally used as arguments to other functions. It is used with in-built functions such as map() and list().
Lambda function with a map()
This in-built function takes in data types such as a list and other data function types. The function is called with all the elements in a list and returns a new list containing elements returned from the original list.
Here’s is an example illustrating how we can use the map() function with the lambda functions to get the cube values of every integer in a list
num_list=[1,3,5,7,9,11,4]
cube_list = list(map(lambda x: x**3, num_list))print(cube_list)
OUTPUT
Lambda functions with filter()
This in-built function takes in data types such as a list and other functions as parameters. The function argument is called with the elements in a list and returns a new list containing elements in the original list that are evaluated to be true.
Here is an example of a filter () function in a program that filters out odd numbers from a specified list.
num_list=[1,3,2,5,8,7,9,11,14,4]
odd_list = list(filter(lambda x: (x % 2!=0), num_list))print(odd_list)
OUTPUT
We have now come to the end of this session. Hope you have had a nice time coding. In our next session we will look at something else. Have a time coding.
Comments
Post a Comment
Please do not enter any spam link in the comment box.