Lambda functions in python - Letsprogram

Share:
We have built-in functions in python and we can create a user-defined function as well by using the keyword def and the function name. We use the function names because it is easy to call the function again. What if we never give the function a name?

It becomes anonymous this function is called anonymous function or lambda. Anonymous functions are created when the function is very small like one expression. These anonymous functions are created by using the keyword called lambda.    
Lamda function
In python, we can use a function to call another function. Because in python everything is considered an object. Lambda functions can be used wherever function objects are used. Like nested function definitions, lambda functions can reference variables from the containing scope:

>>>def increase(n):
          return lambda a:a+n

>>>fun = increase(20)
>>>fun(10)
30
>>>fun(0)
30

Lambda function can take multiple arguments as well 

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

The main point you should understand here is lambda is a function. 
>>>type(lambda x:x+1)
<class function>

Note: Use anonymous function when it is required for a short amount of scope

When you defined a normal function instead of lambda function you have to allocate the space for the function name and scope will be throughout the function if it not defined in the class. When you use a lambda function instead of the normal user-defined function then you do not have to waste the memory and its scope will be small not the entire program.

To read any python programming books check this link

No comments

F