Python Lambda Functions
A Lambda function in Python is an anonymous function defined with the keyword lambda
. They are handy when you need a function for a short period of time and do not want to define a full function using def
. Let’s break it down further.
Main characteristics
- Anonymous: Lambda functions do not have a name unless you assign one explicitly.
- Single Expression: Lambda functions consist of a single expression to be computed.
- Short-Lived: They are usually used for short, temporary operations.
Syntax of Lambda Functions
lambda arguments: expression
lambda
: The keyword used to define the function.arguments
: A comma-separated list of inputs, just like regular functions.expression
: One expression whose value is returned. There is no need for areturn
statement as it is implied.
How Lambda Functions Differ from Regular Functions
Feature | Lambda Function | Regular Function |
---|---|---|
Keyword | lambda | def |
Function Name | Anonymous (can be assigned to a variable) | Requires a name |
Number of Statements | Single expression | Can have multiple statements |
Reusability | Typically for short-term use | Used for reusable, complex logic |
Examples
- Basic Example:
# Regular function
def add(a, b):
return a + b
# Lambda function
add_lambda = lambda a, b: a + b
print(add(3, 5)) # Output: 8
print(add_lambda(3, 5)) # Output: 8
2. Using Lambda with Built-in Functions:
map()
: Applies a function to all items in an iterable.
numbers = [1, 2, 3, 4]
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # Output: [1, 4, 9, 16]
filter()
: Filters items based on a condition.
numbers = [1, 2, 3, 4]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # Output: [2, 4]
sorted()
: Sorts items based on a key.
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda x: x[1])
print(sorted_points) # Output: [(5, 0), (3, 1), (1, 2)]
3. Using Lambda Inside Another Function:
def multiplier(n):
return lambda x: x * n
times_three = multiplier(3)
print(times_three(10)) # Output: 30
Advantages of Lambda Functions
- Concise Syntax: Saves space and reduces boilerplate.
- Readability: Perfect for simple operations.
- No Naming Required: You don’t need to assign a name if it’s a one-time use.
Drawbacks of Lambda Functions
- Single Expression: A lambda can not have multiple statements or complex logic.
- Debugging: Naming is a principal factor in tracing lambda function errors.
- Readability: If overused or used on complex logic, readability may suffer.
When to Use Lambda Functions
- Short-lived, small functionality.
- Inline functions, especially with higher-order functions like
map()
,filter()
, andreduce()
. - When defining small throwaway functions.
When Not to Use Lambda Functions
- When the logic involves more than one expression.
- When the function needs to be reused at multiple locations.
- When clarity and maintainability are a priority.