Lambda Function
What Is a Lambda Function?
- A lambda function is a small, anonymous function in Python. It can take any number of arguments but can only have one expression.
Syntax:
The syntax for a lambda function is:
pythonlambda arguments: expression- The expression is executed and the result is returned.
Examples:
- Simple Lambda Function:
Add 10 to argument
aand return the result:pythonx = lambda a: a + 10 print(x(5)) # Output: 15
- Multiple Arguments:
Multiply argument
awith argumentb:pythonx = lambda a, b: a * b print(x(5, 6)) # Output: 30Summarize arguments
a,b, andc:pythonx = lambda a, b, c: a + b + c print(x(5, 6, 2)) # Output: 13
Why Use Lambda Functions?
Lambda functions are particularly useful as anonymous functions inside other functions. For example, they can be used to create functions that multiply a given number by an unknown number:
pythondef myfunc(n): return lambda a: a * n mydoubler = myfunc(2) print(mydoubler(11)) # Output: 22 mytripler = myfunc(3) print(mytripler(11)) # Output: 33
More Examples:
- Lambda Function with No Arguments:
A lambda function that returns a fixed value:
pythonsix = lambda: 6 print(six()) # Output: 6
- Recursive Lambda Function:
A lambda function to calculate the factorial of a number:
pythonfactorial = lambda a: a * factorial(a - 1) if a > 1 else 1 print(factorial(5)) # Output: 120
- Returning a Lambda Function:
A function that returns a lambda function:
pythondef myfunc(n): return lambda a: a ** n square = myfunc(2) cube = myfunc(3) print(square(3)) # Output: 9 print(cube(3)) # Output: 27
Exercises:
- Simple Calculation:
Write a lambda function that adds 5 to a given number.
pythonadd_five = lambda x: x + 5 print(add_five(10)) # Output: 15
- Conditional Lambda:
Write a lambda function that returns "Even" if a number is even, and "Odd" if a number is odd.
pythoncheck_even_odd = lambda x: "Even" if x % 2 == 0 else "Odd" print(check_even_odd(7)) # Output: Odd
- Lambda in a Function:
Create a function that takes a number and returns a lambda function to multiply any given number by that number.
pythondef multiplier(n): return lambda x: x * n times_three = multiplier(3) print(times_three(5)) # Output: 15
Summary:
- Lambda functions in Python are concise, anonymous functions that are useful for small, quick operations. Practice creating and using lambda functions to get comfortable with this powerful feature!