Creating Lambda Functions
Basic Lambda Function Creation
Lambda functions provide a concise way to create small, anonymous functions in Python. Here's how to create them:
## Basic lambda function syntax
simple_lambda = lambda x: x * 2
print(simple_lambda(5)) ## Output: 10
Lambda Function Parameters
Single Parameter Lambda
## Single parameter lambda
square = lambda x: x ** 2
print(square(4)) ## Output: 16
Multiple Parameters Lambda
## Multiple parameter lambda
multiply = lambda x, y: x * y
print(multiply(3, 4)) ## Output: 12
Lambda Function Use Cases
Sorting with Lambda
## Sorting a list of tuples
students = [('Alice', 85), ('Bob', 75), ('Charlie', 92)]
sorted_students = sorted(students, key=lambda student: student[1], reverse=True)
print(sorted_students)
## Output: [('Charlie', 92), ('Alice', 85), ('Bob', 75)]
Mapping with Lambda
## Transforming list elements
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) ## Output: [1, 4, 9, 16, 25]
Lambda Function Workflow
graph TD
A[Lambda Function Definition] --> B{Input Parameters}
B --> C[Single Expression Evaluation]
C --> D[Return Result]
Common Lambda Function Patterns
Pattern |
Example |
Description |
Simple Calculation |
lambda x: x * 2 |
Multiply input by 2 |
Conditional Return |
lambda x: x if x > 0 else 0 |
Return x if positive |
Multiple Operations |
lambda x, y: x + y if x > y else y |
Conditional addition |
Advanced Lambda Techniques
Lambda with Conditional Logic
## Conditional lambda function
check_positive = lambda x: "Positive" if x > 0 else "Non-positive"
print(check_positive(5)) ## Output: Positive
print(check_positive(-3)) ## Output: Non-positive
Lambda in Function Arguments
## Using lambda as a function argument
def apply_operation(x, operation):
return operation(x)
result = apply_operation(10, lambda x: x * 2)
print(result) ## Output: 20
LabEx Pro Tip
When working with lambda functions, remember they are best suited for simple, one-line operations. For more complex logic, traditional function definitions are recommended.
Potential Pitfalls
- Lambda functions are limited to single expressions
- They can reduce code readability if too complex
- Not suitable for multi-line operations