#17 Lambda-funk / Python Lessons for Beginners

by Alex
#17 Lambda-funk / Python Lessons for Beginners

Previous lesson: Functions in Python A lambda function is a small, anonymous function. It can take any number of arguments, but at the same time have only one expression.

Syntax

lambda arguments : expression After executing the expression – the result is returned. Lambda functions can take any number of arguments. lambda multiplies the argument a by the argument b and outputs the result:

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

Output:

30

And this function sums the arguments a, b, and c and outputs the result:

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

Output:

13

Why use lambda functions?

The power of a lambda is better seen when you use it as an anonymous function within another function. Say you have a function definition that takes one argument, and that argument will be multiplied by an unknown number:

def myfunc(n):
return lambda a: a * n

Use this function definition to create a function that always doubles the number you send:

def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(2)
print(mydoubler(11))

Output:

22

Or use the same function definition to make a function that always triples a number:

def myfunc(n):
return lambda a: a * n
mytripler = myfunc(3)
print(mytripler(11))

Conclusion:

33

Or, use the same definition to make both functions in the same program:

def myfunc(n):
return lambda a: a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))

Output:

22
33

Use the lambda function when an anonymous function is needed in a certain part of the code, but not throughout the script.

Related Posts

LEAVE A COMMENT