A Lambda Function is a small anonymous function that can have any number of arguments but only one expression.
Lambda functions are useful when you need a simple function for a short period of time.
Lambda Function Syntax
Syntax
lambda arguments : expression
Example
x = lambda a: a + 10
print(x(5))
Output:
15
Lambda Function with Multiple Arguments
Example
x = lambda a, b: a * b
print(x(5, 4))
Output:
20
Lambda Function with Three Arguments
Example
x = lambda a, b, c: a + b + c
print(x(10, 20, 30))
Output:
60
Using Lambda Inside a Function
Example
def multiplier(n):
return lambda a: a * n
double = multiplier(2)
print(double(10))
Output:
20
Lambda with map()
The map() function applies a function to each item in an iterable.
Example
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x * 2, numbers))
print(result)
Output:
[2, 4, 6, 8]
Lambda with filter()
The filter() function filters elements based on a condition.
Example
numbers = [1, 2, 3, 4, 5, 6]
result = list(filter(lambda x: x % 2 == 0, numbers))
print(result)
Output:
[2, 4, 6]
Lambda with sorted()
Example
students = [
{"name": "John", "age": 22},
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 25}
]
result = sorted(students, key=lambda x: x["age"])
print(result)
Output:
[{'name': 'Alice', 'age': 20}, {'name': 'John', 'age': 22}, {'name': 'Bob', 'age': 25}]
Why Use Lambda Functions?
- Creates short and simple functions.
- Useful for one-time operations.
- Commonly used with
map(),filter(), andsorted(). - Reduces the need for creating separate functions.
Summary
- Lambda functions are anonymous functions.
- They are created using the
lambdakeyword. - They can accept multiple arguments.
- They can contain only one expression.
- Lambda functions are often used with
map(),filter(), andsorted(). - They help write concise and readable code.