What is a lambda function?
AI-Powered Answer
✓ Answered
A lambda function in Python is a small anonymous function defined using the `lambda` keyword. It can take any number of arguments but can only have one expression.
Definition
Lambda functions are also known as anonymous functions because they are not declared with the standard def keyword. They are typically used for short, single-expression functions, often as arguments to higher-order functions like map(), filter(), and sorted().
Syntax
The basic syntax for a lambda function is lambda arguments: expression. The arguments are optional, and the expression is evaluated and returned.
python
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8
Key Characteristics
- Anonymous: They don't have a name.
- Single Expression: They can only contain one expression, which is implicitly returned.
- Inline: Often used for short, throwaway functions that are not needed elsewhere.
- Can take multiple arguments: Like regular functions, they can accept zero or more arguments.
Common Use Cases
- With
map(): Applying a function to all items in an iterable. - With
filter(): Filtering elements from an iterable based on a condition. - With
sorted(): Defining a custom sort key for sorting collections. - GUI event handlers: For simple callback functions.
python
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x * x, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]
Limitations
- Single expression only: Cannot contain multiple statements, loops, or complex logic.
- No docstrings: Lack the ability to include a docstring for documentation.
- Readability: Overuse or complex lambda expressions can reduce code readability compared to named functions.