Middle
What is a lambda function in Python and when is it used?
sobes.tech AI
Answer from AI
A lambda function in Python is an anonymous function defined using the lambda keyword. It can contain only one expression and returns its result. Lambda functions are often used for short, simple operations, for example, in higher-order functions (map, filter, sorted) or when you need to quickly pass a function as an argument.
Example:
# Sorting a list of tuples by the second element
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # [(2, 'a'), (1, 'b'), (3, 'c')]