Python: lambda Function

Shumaiya Akter Shammi
3 min readOct 23, 2020

Lambda is a single-line anonymous function which can take any number of arguments but it can have only one expression.

Some keywords:

  • This function can take any number of arguments but can have a single expression.
  • This function may or may not be return any value.
  • Syntax: lambda argument/arguments : expression

Simple syntax of lambda function and its usage:

lambda function with one argument and one expression

In this section of code below, we can see that the lambda function is taking 2 arguments but its expression is single.

Let’s see the next snippet if we want to try with multiple expression.

lambda function with 2 argument, one expression
lambda function with multiple argument (Line-1,2) & multiple expression (Line-3,4)

In this code snippet, we can see that we provide 3 arguments in the lambda function and it is working perfectly. But in the second part of code we provide 2 expression which gives us an error. So, it is clear that lambda function can take one expression only.

But, here is a confusion can arise in learner’s mind that how do we call this lambda function?

From the above keyword we saw that lambda is an anonymous function that’s why we don’t need to assign any function name. We can easily call this function using the identifier (w, x, y, z-From above code snippet).

Till now who have confusion about this anonymous function, the next code snippet will remove their confusion.

In this code snippet below, the lambda function and the sum(var1, var2, var3) function is doing the same thing. So, we can say that lambda is a anonymous function and very easy to use. Lets go through another example to clear our concept more clear.

lambda function and user defined function

In the next code snippet, we are doing actually a multiplication. At first, we make a function, then we use lambda function inside it. 5th line of this code, we are actually call the function multiplication and give a parameter or the value of n. Then in the 6th line of this code we are calling lambda function and the value of var1. Then it provides us the result of var1*n.

lambda function inside a user-defined function

In the next code snippet, the functionality is more clear. Here we can see that, we are calling the multiplication() function. Then in the 6th line of code we are calling the function lambda using the identifier mul and doing the operation var1*var2*n = 2*2*5 = 20

lambda function inside a user-defined function (2 argument)

We can also use lambda function to iterate a list and tuple. First part of this code, we can see that we have used a function filter(). Syntax of filter() function is:

filter(object, iteration)

Here, in the object part we have to use a lambda function. By this function, we can iterate a list or a tuple easily.

lambda function to iterate a sequence (list, tuple)

--

--