As discussed in the previous module, we know that there are three types of Python Functions. One of them is an anonymous function. Anonymous functions 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 the keyword, ‘lambda’. Since anonymous functions are defined using the lambda keyword, they are also sometimes referred to as lambda functions.
In this module, we will learn all about lambda functions in Python in order to get started with them. Following is the list of all topics covered in this module.
So, without any further delay, let’s get started.
The lambda keyword is used to define anonymous functions, that is, functions without names. Python lambda functions are not much different from the regular functions that are defined using the def keyword.
Syntax of a lambda function in Python:
lambda arguments: expression Here’s an example of Lambda in Python. (lambda a,b: a+b) (4,6) If we execute the above code line, the output will be 10.
In the above example, we simply performed addition operation using the lambda function in Python. If we compare this example to the syntax of the Python 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 arguments as soon as we defined the lambda function (values being 4 and 6, respectively). The same operation can be performed using a regular function as shown below:
def add(a,b): return a+b add(4,6) Output: 10
Now, the question here is that if we can perform the same operation using a regular function, then why do we need a lambda function in Python? Moving forward, let’s find out why we need Python lambda functions at all.
A lambda function is not an absolute necessity in Python, but using a 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. Now, in what all situations using a lambda function is beneficial? Following are some of the situations where using a lambda function is preferred.
So, to summarize, a lambda function behaves like a regular function, takes an argument, and returns a value but is not bound to any name or identifier. There is no need to use the return statement in a lambda function in Python; it will always return the value obtained by evaluating the lambda expression in Python.
With this, we come to an end of this module on Python Tutorial. Here we learn about what is Lambda in Python. And how to use Python Lambda function with the help of examples. We also learned why we would use them. Further, we talked about the properties of lambda functions in Python.
Now, if you want to know why python is the most preferred language for Data Science, you can go through this blog on Python for Data Science.Previous Next
Download Interview Questions asked by top MNCs in 2019?