Lambda Function Basics
What is a Lambda Function?
A lambda function in Python is a small, anonymous function that can have any number of arguments but can only have one expression. 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:
lambda arguments: expression
Simple Examples
Single Argument Lambda
## Square a number
square = lambda x: x ** 2
print(square(5)) ## Output: 25
Multiple Arguments Lambda
## Add two numbers
add = lambda x, y: x + y
print(add(3, 4)) ## Output: 7
Key Characteristics
Characteristic |
Description |
Anonymous |
No name required |
Single Expression |
Can only contain one expression |
Compact |
Shorter than regular function definition |
Inline Usage |
Often used with built-in functions |
Use Cases
graph TD
A[Lambda Functions] --> B[Sorting]
A --> C[Filtering]
A --> D[Mapping]
A --> E[Functional Programming]
Common Use Scenarios
- Sorting with Key Function
## Sort list of tuples by second element
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
- Filtering Lists
## Filter even numbers
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
Limitations
- Not suitable for complex logic
- Single expression constraint
- Reduced readability for complex operations
Best Practices
- Use lambda for simple, one-line operations
- Prefer named functions for complex logic
- Consider readability when using lambda functions
By understanding lambda functions, you can write more concise and functional Python code with LabEx's powerful programming environment.