In Python there is a specific function that is called Python Lambda function. Python Lamda function is used as anonymous function. As we have learned before, normally functions are defined with a keyword “def”. But anonymous functions are defined with ”lambda” keyword.
To define a lambda function, we use “lambda” keyword firstly. After that we use the argument name. Then we use a colon and lastly, we deifne the expression. There can be one more arguments but we can use only one expression in a python lambda function.
Let’s do an example and learn this anonymous functions better.
In this example, the argument is y. And the expression is y *2. We define this function and assign it to x. The return of this code will be according to the used value for x. The output of this code will be:
In the above example, we had only one arguments. Now, let’s use one more argument for our lambda function.
You can also watch the video of this Python Lesson!
Here, our arguments are a and b. And the expression is a*a-b*b. So, the output of this code will be 4*4-3*3=7.
Here, we have used two arguments. We can increase the number of these arguments according to our need. The key point is this, we can use only one expression in a python lambda function.
Python lambda function is used with higher-order functions also. These functions takes other functions as arguments. So what are these functions used with lambda function? These are:
Now, let’s learn what are these functions and how can we use them with lambda function.
Python Filter function is a function that takes a lambda function as an argument with also another argument.
For example if we would like to create a new list from an existing list that includes only even list items, we can use below code:
Here, filter function takes two arguments. The first one is lambda function and the second one is list.
The output of this code will be:
In another example, we can control the items of a list if it is higher than a value or not.
For this code, the output will be:
Map() function is another function used with python lambda function. It also receives another arguments.
Below, we will do the same examples above with map fucntion.
The outout of this code will be:
As you can see above, map function has checked all the items in the list and according to their value, it has returned True or False. With filter function, the new list was created with the values of the items. But with map function, the new list has created with the result of expression(x>5), True or False.
We can use map function with also a calculation expression.
This time the code will give us the results of each calculation:
In this python lambda function lesson, we have talked about both how to use lambda function alone and with other high-order functions. We have learned how to use python filter function and python map function with lambda function.