Lambda Functions In Python
Python Lambda Functions: Anonymous Functions
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
1. Syntax
The syntax for a lambda function is:
lambda arguments : expression
The expression is executed and the result is returned.
x = lambda a : a + 10
print(x(5)) # Output: 15
2. Multiple Arguments
Lambda functions can take multiple arguments.
# Multiple arguments
x = lambda a, b : a * b
print(x(5, 6)) # Output: 30
# Even more arguments
x = lambda a, b, c : a + b + c
print(x(5, 6, 2)) # Output: 13
3. Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside 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
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11)) # Output: 22
print(mytripler(11)) # Output: 33
4. Common Use Cases
| Function | Description | Example |
| :--- | :--- | :--- |
| map() | Applies logic to all items in a list | map(lambda x: x*2, [1, 2, 3]) |
| filter() | Filters a list based on a condition | filter(lambda x: x > 5, [2, 7, 1]) |
| sorted() | Uses lambda as a custom sorting key | sorted(list, key=lambda x: x[1]) |
filter():
ages = [5, 12, 17, 18, 24, 32]
adults = list(filter(lambda x: x >= 18, ages))
print(adults) # Output: [18, 24, 32]
map():
numbers = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8]
5. Summary Check
- Anonymous: They don't have a name (unless assigned to a variable).
- Single Expression: No multiple lines of logic.
- One-time Use: Best for short-lived logic inside higher-order functions.