What is lambda binding in Python?

ProgrammingPython

When a program or function statement is executed, the current values of formal parameters are saved (on the stack) and within the scope of the statement, they are bound to the values of the actual arguments made in the call. When the statement is exited, the original values of those formal arguments are restored. This protocol is fully recursive. If within the body of a statement, something is done that causes the formal parameters to be bound again, to new values, the lambda-binding scheme guarantees that this will all happen in an orderly manner.

there is only one binding for x: doing x = 5 just changes the value in the pre-existing binding. That's why default parameter used to assign a value directly to a lambda's parameter.

Example

def function(x):
   a = lambda x=x: x
   x = 5
   b = lambda: x
   return a,b
aa, bb = function(2)
aa()
bb()

Output

5

Python allows you to create anonymous function i.e function having no names using a facility called lambda function. lambda functions are small functions usually not more than a line. The result of the expression is the value when the lambda is applied to an argument.

raja
Sri
Published on 27-Jun-2019 19:49:54
Advertisements