Lambda Function Basics
Introduction to Lambda Functions
Lambda functions, also known as anonymous functions, are a powerful feature in Python that allow you to create small, one-line functions without formally defining them using the def
keyword. These compact functions are particularly useful for short, simple operations.
Basic Syntax
The basic syntax of a lambda function is as follows:
lambda arguments: expression
Here's a simple example to illustrate:
## Traditional function
def square(x):
return x ** 2
## Equivalent lambda function
square_lambda = lambda x: x ** 2
## Using the lambda function
print(square_lambda(5)) ## Output: 25
Key Characteristics
Characteristic |
Description |
Anonymity |
No formal name required |
Single Expression |
Can only contain one expression |
Conciseness |
Shorter and more compact than regular functions |
Immediate Use |
Often used with higher-order functions |
Common Use Cases
1. Sorting with Lambda
## Sorting a list of tuples by second element
students = [('Alice', 85), ('Bob', 75), ('Charlie', 92)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)
## Output: [('Bob', 75), ('Alice', 85), ('Charlie', 92)]
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]
Workflow of Lambda Functions
graph TD
A[Input Arguments] --> B[Lambda Function]
B --> C[Single Expression Evaluation]
C --> D[Return Result]
Limitations
- Cannot contain multiple expressions
- Limited to simple operations
- Less readable for complex logic
Best Practices
- Use lambda for simple, one-line operations
- Prefer named functions for complex logic
- Combine with built-in functions like
map()
, filter()
, and sorted()
By understanding lambda functions, you'll enhance your Python programming skills and write more concise code. At LabEx, we encourage exploring these powerful Python features to become a more efficient programmer.