Lambda Functions Python

Lambda functions Python (Anonymous functions)

So far, we have written some different functions. The way we write our own functions is very simple. We just write the def keyword, followed by the name of the function. But what if, we could create a function, without a name? Is it possible? Well, this is where the anonymous functions or the lambda functions come into the picture. Here, we are going to create such functions, which are going to be anonymous.

These functions can be often used when we need to create such functions, which are specific in use, and often one-liners. This is a feature for conveniently writing such functions. Let’s have a look at how we can write the lambda functions or anonymous functions.

First of all, we have to use the keyword lambda. After that, we have to list the parameters (if there is more than one parameter, just separate them with commas), and then give a colon, and then write the expression. This function has no name, and it returns a function object, which is assigned to the variable. Let’s have a look at an example, where we would write a function, which returns the square of the given number. Let’s have a look at how we can do this, with the help of the lambda function.

Lambda Functions Python

As you can see, we have used the lambda keyword, followed by the different parameters (in this case, there is only one parameter, which is number), and after that, we are getting a colon here, and then, we are writing the expression, which calculates the square for us. We are assigning this to the variable. So, when we call the function (as you can see in the last instruction, in the above program), with a value of 6, the function returns the square of the given number. You can also try the above program, to understand the lambda function.

Let’s have one more example, where we would just calculate the cube of the given number. Now, Let’s have a look at the code.

As you can see, we have the function here, which is just taking a number, and returning its cube. You can try doing this program and execute it and observe the output. So, this was about the lambda functions or anonymous functions. You can give them a try, and we can use them as and when required.