Lambda Fundamentals
What is a Lambda Function?
Lambda functions, also known as anonymous functions, are small, inline functions defined without a name. They are powerful tools in Python for creating concise and efficient code. Unlike regular functions defined with the def
keyword, lambda functions are created using the lambda
keyword.
Basic Syntax
The basic syntax of a lambda function is straightforward:
lambda arguments: expression
Here's a simple example:
## Regular function
def add(x, y):
return x + y
## Equivalent lambda function
add_lambda = lambda x, y: x + y
print(add(3, 5)) ## Output: 8
print(add_lambda(3, 5)) ## Output: 8
Key Characteristics
Characteristic |
Description |
Conciseness |
Single-line function definition |
Inline Creation |
Created at the point of use |
Limited Complexity |
Best for simple operations |
Functional Programming |
Commonly used with map() , filter() , reduce() |
Common Use Cases
1. Sorting with Custom Key
## Sorting a list of tuples by second element
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) ## Output: [(1, 'one'), (3, 'three'), (2, 'two')]
2. 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]
## Square each number in a list
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) ## Output: [1, 4, 9, 16, 25]
Limitations
graph TD
A[Lambda Function] --> B{Limitations}
B --> C[Single Expression]
B --> D[No Multiple Statements]
B --> E[Limited Readability]
B --> F[No Docstrings]
While lambda functions are powerful, they have some limitations:
- Can only contain a single expression
- Cannot include multiple statements
- Less readable for complex operations
- Cannot have docstrings
Best Practices
- Use lambda functions for simple, one-line operations
- Prefer named functions for complex logic
- Consider readability when creating lambda functions
By understanding these fundamentals, you'll be able to leverage lambda functions effectively in your Python programming, especially when working with functional programming techniques. LabEx recommends practicing these concepts to gain proficiency.