As discussed in the previous module, we know that there are three types of functions in Python. One of them is an anonymous function. Anonymous functions in python are the functions without a name. Now to define a normal function, we use the keyword def. Similarly, to define an anonymous function we use a keyword lambda. Since anonymous functions are defined using lambda keyword, they are also sometimes referred to as lambda functions.
In this module, we will learn all about the lambda functions in Python in order to get started with it. Following is the list of all the topics that we will cover in this module, in case you need to jump to a specific one.
So, without any further delay, Let’s get started.
Watch this lambda expression in Python video
Lambda keyword is used to define anonymous functions, that is, the functions without name. The lambda functions are not that much different from the regular functions that are defined using the def keyword.
Syntax of a lambda function:
Let’s look at the following example to understand the syntax better.
If we execute the above code line, the output will be 10.
In the above example, we have simply performed addition operation using lambda function. If we compare this example to the syntax of the lambda function, a and b are the arguments and a+b is the expression that is being evaluated and returned and the whole statement is the lambda function. We have passed the values in the arguments as soon as we have defined the lambda function (values being 4 and 6 respectively). The same operation can be performed using a regular function as shown below:
Now the question here is that if we can perform the same operation using a regular function then why do we need lambda function? So, moving forward let’s find out why we need Lambda functions at all.
Lambda function is not an absolute necessity in Python, but using lambda function in certain situations definitely makes it a bit easier to write the code. Not just that, it also makes the written code a bit cleaner. What kind of situation, you might be wondering? The following listed are some of the situation where using lambda function is preferred.
So, to summarize, a lambda function behaves like a function, takes argument and returns a value but is not bound to any name or identifier. There is no need to use the return statement in Lambda function, it will always return the value obtained by evaluating the lambda expression.
With this we come to an end of this module. The next module highlights the built-in functions in Python. See you there!Previous Next
Download Interview Questions asked by top MNCs in 2019?