Overview
Lambda functions, also known as anonymous functions, are small, unnamed functions defined using the lambda
keyword in Python. They are typically used for short, simple operations and can take any number of arguments but only have one expression.
Syntax
lambda arguments: expression
Key Characteristics
Anonymous: Lambda functions are defined without a name.
Single Expression: They contain a single expression, not a block of statements.
Short-Lived: Often used for a short period of time, such as in arguments to higher-order functions like
map()
,filter()
, andsorted()
.
Basic Example
# Standard function
def add(x, y):
return x + y
# Equivalent lambda function
add_lambda = lambda x, y: x + y
# Usage
print(add(2, 3)) # Output: 5
print(add_lambda(2, 3)) # Output: 5
Common Uses
1. In Higher-Order Functions
map()
: Applies a function to all items in an input list.
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # Output: [1, 4, 9, 16, 25]
filter()
: Filters items out of an input list.
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4]
sorted()
: Sorts items of an iterable based on a key function.
points = [(1, 2), (4, 1), (5, -1), (3, 3)]
sorted_points = sorted(points, key=lambda x: x[1])
print(sorted_points) # Output: [(5, -1), (4, 1), (1, 2), (3, 3)]
2. Inline Use
For Quick Calculations
result = (lambda x, y: x * y)(3, 4)
print(result) # Output: 12
Limitations
Readability: Can reduce code readability if overused or used for complex functions.
Single Expression: Limited to single expressions; cannot contain multiple statements or annotations.
Comparison with def
Functions
Lambda Function:
multiply = lambda x, y: x * y
print(multiply(2, 3)) # Output: 6
Def Function:
def multiply(x, y):
return x * y
print(multiply(2, 3)) # Output: 6
Best Practices
Simplicity: Use for simple operations.
Temporary Use: Ideal for short-term use in a limited scope.
Readability: Avoid using lambda functions for complex operations; prefer named functions for clarity.
Advanced Examples
Nested Lambdas
nested_lambda = lambda x: (lambda y: x + y)
adder = nested_lambda(10)
print(adder(5)) # Output: 15
Lambda with Conditional Expressions
max_lambda = lambda x, y: x if x > y else y
print(max_lambda(10, 20)) # Output: 20
Conclusion
Lambda functions in Python provide a compact and powerful way to create anonymous, single-expression functions on the fly. They are most useful for short, simple operations, particularly in functional programming contexts with higher-order functions. However, their use should be balanced with considerations of readability and maintainability.