Python Lambda | Syntax | lambda arguments | def myfunc(n)


Python Lambda | Syntax | lambda arguments | def myfunc(n)

Python Lambda

A lambda operate could be a tiny anonymous operate.

A lambda operate will take any variety of arguments, however will solely have one expression.

Syntax

lambda arguments : expression

The expression is dead and also the result’s returned:

Example
A lambda operate that adds ten to the quantity passed in as Associate in Nursing argument, and print the result:

x = lambda a : a + ten
print(x(5))

Lambda functions will take any variety of arguments:

Example
A lambda operate that multiplies argument a with argument b and print the result:

x = lambda a, b : a * b
print(x(5, 6))

Example

A lambda operate that sums argument a, b, and c and print the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))

Why Use Lambda Functions?

The power of lambda is best shown once you use them as Associate in Nursing anonymous operate withinanother operate.

Say you have got a operate definition that takes one argument, which argument are increased with Associate in Nursing unknown number:

def myfunc(n):
come back lambda a : a * n

Use that operate definition to create a operate that forever doubles the quantity you send in:

Example
def myfunc(n):
come back lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Or, use identical operate definition to create a operate that forever triples the quantity you send in:

Exampledef myfunc(n):

come back lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))
Or, use identical operate definition to create each functions, within the same program:
Example
def myfunc(n):
come back lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11)) 
print(mytripler(11))

Python Lambda | Syntax | lambda arguments | def myfunc(n)

Have any Question or Comment?

Leave a Reply

Your email address will not be published. Required fields are marked *

Categories