What is lambda function in python? | anonymous function

we all know we can define a function by using the def keyword

Can we do without def keyword !??

Yess we can let’s see how

Generally, we define functions is by using the def keyword and then we mention the function name as well,

what if we don’t mention the function name If we do that it becomes anonymous and that’s where we can create a function in Python called anonymous functions without name all we can also call them lambda

if we want to create a function normally what we do is we say def

Basic example:

def double(x):
   return x * 2
print (double(5))



what if we want to use a function only once and we don’t want to define the name of the function and if we want to only have one expression

In functions, we can pass functions to a function The way we pass objects we can also pass functions because functions are objects in Python,

so it’s not defining a function we can define a function when we want to use it directly

which is lambda because the anonymous


lambda arguments: expression


double = lambda x: x * 2




In this above simple example, we are using lambda for the most simple operation,

firstly the thing is we’re declaring the variable and the operations for that variable in a single line hence the code becomes simplified when compared to the conventional code method

secondly, we’re using the print function for displaying the output directly by giving the value of the variable which we created in the lambda expression

most importantly a function that  we want to use  is lambda the thing is as we have known that functions are objects in Python

so of course we need to assign it to a variable to get output from it for that

here we've used double as variable
and x is argument and X*2 is 

remember we can pass any number of arguments but it should be only of one expression 

How many arguments can be created in lambda function ?

generally, there is no limit to the number of arguments that can be passed inside the lambda function

In conclusion, we can use any number of arguments we need for our convenience

to understand more clearly we’ll see an example

Example 2

k= lambda a,b : a+b
print (k(8,7))




In the above code, we’ve created 2 parameters for our lambda function say ‘a’ and ‘b’ which is separated by a comma

for instance, we’re performing a simple addition operation here for a better understanding, here we created 2 variables after that we’ve given the expression that to be executed is addition

and we calling the variable ‘k’ which has the byproduct of the operation we performed and printing directly

In conclusion with the above example we have seen how to create and execute with more than one arguments using the anonymous function or the Lambda function

We will be happy to hear your thoughts

Leave a reply

Open chat
Scan the code
Can we help you?