Practical Lambda Examples
Real-World Lambda Applications
Lambda functions are powerful tools in Python for creating concise and efficient code across various scenarios.
Filtering Lists
## Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4, 6, 8, 10]
## Convert temperatures from Celsius to Fahrenheit
temperatures = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, temperatures))
print(fahrenheit) ## Output: [32.0, 50.0, 68.0, 86.0, 104.0]
Sorting Complex Data
## Sort dictionary by specific key
employees = [
{'name': 'Alice', 'age': 30, 'salary': 5000},
{'name': 'Bob', 'age': 25, 'salary': 4500},
{'name': 'Charlie', 'age': 35, 'salary': 6000}
]
sorted_by_salary = sorted(employees, key=lambda emp: emp['salary'], reverse=True)
print(sorted_by_salary)
Lambda Use Cases
Scenario |
Lambda Benefit |
List Comprehensions |
Compact transformations |
Functional Programming |
Inline function creation |
Data Processing |
Quick data manipulations |
Advanced Functional Programming
graph LR
A[Lambda Functions]
A --> B[filter()]
A --> C[map()]
A --> D[reduce()]
Reducing Lists
from functools import reduce
## Calculate product of list elements
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) ## Output: 120
Error Handling and Validation
## Validate email format
def validate_email(email):
return len(list(filter(lambda x: '@' in x, [email]))) > 0
emails = ['[email protected]', 'invalid-email', '[email protected]']
valid_emails = list(filter(validate_email, emails))
print(valid_emails) ## Output: ['[email protected]', '[email protected]']
- Lambda functions are best for simple operations
- For complex logic, use regular functions
- Optimize based on specific use cases
Enhance your Python skills with these practical lambda examples from LabEx!