Lambda Functions

Last updated Aug 10, 2021

Lambda Functions

In Python Lambda functions are also known by the name of Anonymous function. Generally, Lambda functions are single-line functions that are declared without any name and these functions can have any number of arguments but they must contain only one expression. These are also known as One-Liner functions. These functions are similar to regular functions and these lambda functions are also written with the help of the def keyword. 

Syntax of Lambda Functions / Anonymous Functions

Let's look at the syntax of Lambda functions:-

lambda arguments : expression

As you can see that the syntax of the Lambda function is written in a single line, this is the reason why these are known as one-liner functions. These functions can take several arguments. 

Now we will take few examples which will explain to us about the use of Lambda Functions / Anonymous Functions

  1. When we have one argument

Here we will take the case when we have only a single argument i.e. a

ans = lambda a : a + 5
print(ans(2))
7  

        2.  When we have two arguments

Now we will take two arguments which are a and b and will use lambda functions with the help of these two arguments

ans = lambda a, b : a * b
print(ans(2, 3))
6  

      3.  When we have three arguments

In this case, we will take three arguments a, b and c, and will use all three arguments in lambda functions

ans = lambda a, b, c : a + b + c
print(ans(2, 3, 4))
9  

So we had understood the use of Lambda functions by taking all the basic examples of lambda functions.

Why use Lambda Functions instead of regular Functions?

As lambda functions are one-liner functions so they are faster than regular def functions. Also, lambda functions provide higher efficiency than def functions. And we use these lambda functions when we require nameless functions for a short span of time. These Lambda Functions are used along with some built-in functions like they are used with map(), filter() and reduce() functions. Lambda Functions does not include any return statement but regular functions include a return statement. Generally, lambda functions contain expressions that are returned by nature. 

Both Functions provide a good framework but Lambda functions provide a better platform than regular def functions.