In Python, a lambda expression (or lambda function) is a way to create small, one-time, anonymous function objects. They are often used for small, one-time operations where a full function definition would be overly verbose.
The syntax for a lambda expression is:
lambda arguments: expression
Here, arguments
is a comma-separated list of arguments, and expression
is a single Python expression that is returned by the lambda.
Code Examples
1. Basic Lambda Function
A simple lambda that takes an argument and multiplies it by 2:
f = lambda x: x * 2
print(f(7)) # Outputs: 14
2. Multiple Arguments
A lambda that takes two arguments and adds them:
add = lambda x, y: x + y
print(add(5, 3)) # Outputs: 8
3. Conditionals
Using a lambda with a conditional expression:
check = lambda x: "Even" if x % 2 == 0 else "Odd"
print(check(4)) # Outputs: Even
4. Using Lambdas with map()
Applying a lambda to each element of a list:
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Outputs: [1, 4, 9, 16, 25]
5. Using Lambdas with filter()
Filtering a list with a lambda:
numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Outputs: [2, 4, 6]
6. Sorting with Lambda
Sorting a list of tuples by the second element:
pairs = [(1, 2), (3, 1), (5, 10), (7, 5)]
pairs.sort(key=lambda x: x[1])
print(pairs) # Outputs: [(3, 1), (1, 2), (7, 5), (5, 10)]
7. Nested Lambda Functions
Using lambdas within lambdas:
nested = lambda x: (lambda y: x + y)
add_five = nested(5)
print(add_five(3)) # Outputs: 8
8. Using Lambda with reduce()
Reducing a list using a lambda:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result) # Outputs: 120
9. Combining Lambdas
Combining multiple lambda functions:
multiply = lambda x: x * 2
add_ten = lambda x: x + 10
result = lambda x: add_ten(multiply(x))
print(result(5)) # Outputs: 20
10. Lambda as an Argument
Passing a lambda as an argument to another function:
def apply_func(func, value):
return func(value)
result = apply_func(lambda x: x + 5, 10)
print(result) # Outputs: 15
Summary
Lambda expressions in Python provide a concise way to create small, anonymous functions. They can be used in a variety of contexts, from simple arithmetic to more complex operations like sorting and filtering. While lambdas are powerful, their use should be limited to situations where they enhance code clarity, as overuse can make code harder to understand.