Home >>Python Tutorial >Python Lambda

Python Lambda

The Python Lambda

This is the Python lambda tutorial. And a lambda is a function in this programming language that is basically defined as a type of a small anonymous function. This particular function can up any number of arguments. However, this function can only have one single expression.  

The Syntax

If the lambda argument is expressions then the expressions can be simply executed and the results can also be returned. For example, if you wish to produce a Python lambda syntax that automatically adds 10 to any number that has been passed in a particular argument and then if you also want to print the result then  
x = lambda a : a + 10

print ( x ( 5 ) )
  We also know that lambda functions can take any number of arguments and this fact can easily be illustrated with the help of the below-mentioned examples. The first example is illustrated for a case where you might want the lambda function to multiply argument a with argument b and then get the results.  
x = lambda a, b : a * b

print (x (5, 6) )
  If you want a lambda function to instead get a sum of argument a, b, and c and then print the results then that is mentioned below.  
x = lambda a, b, c : a + b + c

print (x (5, 6, 2) )
 

The Reason for Using Lambda Function

The Python lambda function is an incredibly powerful function which you can use to its full potential when you use it anonymously inside an already existing function. For example, if you have a function definition that takes up a particular argument and you have already assigned that argument to be multiplied with an unknown number in the method mentioned below.  
def myfunc (n) :

   return lambda a : a * n
  And now if you want to use this above-mentioned function to always double the number you send in then you can do that by following the method mentioned below  
def myfunc ( n ) :

    return lambda a : a * n



mydoubler = myfunc ( 2 )



print (mydoubler ( 11 ) )
  You can also follow the above-mentioned example to triple the number that you send in but you will be required to make a few changes in the Python lambda function for that. And those changes are mentioned below  
def myfunc ( n ) :

   return lambda a : a * n



mytripler = myfunc ( 3 )



print (mytripler ( 11 ) )
  If you wish to add both of those functions in the same program then you can do that too. But for that, you will be required to make a few changes. And those changes are mentioned below.  
def myfunc ( n ) :

   return lambda a : a * n



mydoubler = myfunc ( 2 )

mytripler = myfunc ( 3 )



print (mydoubler ( 11 ) )

print (mytripler ( 11 ) )
  You should also remember that it is best to use the lambda function whenever you need to use an anonymous function for any mentioned short period of time. With this, we complete our Python lambda part of this entire Python tutorial.

No Sidebar ads