Middle
What are lambda functions, what are their limitations, and when does it make sense to use them?
sobes.tech AI
Answer from AI
Lambda functions in Python are anonymous functions created using the lambda keyword. They allow you to define a small function in a single line without a name.
Main syntax:
lambda arguments: expression
Restrictions of lambda functions:
- Contain only one expression, cannot include multiple statements or complex code blocks.
- Do not support type annotations and documentation.
- May be less readable with complex logic.
When to use:
- For simple functions needed only once, such as arguments to higher-order functions (
map,filter,sorted). - When you want to quickly define a short function without declaring it with
def.
Example:
# Sorting a list of tuples by the second element
pairs = [(1, 'one'), (2, 'two'), (3, 'three')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [(1, 'one'), (3, 'three'), (2, 'two')]