Python
[Basic Grammar] Python Lambda
grace21110
2023. 10. 21. 17:50
반응형
A lambda function is small anonymous function.
- Syntax
lambda arguments : expression
Example
Add 10 to argument a, and return the result.
x = lambda a : a + 10
print (x(8))
Multiply argument a with argument b and return the result.
x = lambda a,b : a * b
print (x(8, 1))
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Exercises
Write a Python program that defines a lambda function multiply_by which takes a number n as an argument and returns a new lambda function. The new lambda function should take another number x as an argument and return the result of multiplying n by x. Then, use this lambda function to calculate the product of 5 and 7.
def multiply_by(n):
return lambda a : a * n
triple = multiply_by (3)
result = triple (5)
print ("Result:", result)
Result: 15