lambda Function (Anonymous Functions)Creates a small, single-expression function without a name. Useful for short operations where a full def function is overkill.
lambda arguments: expression
lambda: Keyword to create a lambda function.arguments: One or more arguments the function accepts (like in a def function), separated by commas.:: Separates the arguments from the expression.expression: A single expression. The value of this expression is what the lambda function returns.Example:
# A lambda function that adds two numbers
add = lambda a, b: a + b
print(add(5, 3)) # Output: 8
# A lambda function that squares a number
square = lambda x: x * x
print(square(4)) # Output: 16
lambda is often used with functions that take other functions as arguments, like sorted(), map(), and filter().
Example with sorted():
Sorting a list of tuples based on the second element:
data = [('apple', 2), ('banana', 1), ('cherry', 3)]
# Sort the list using a lambda function to specify the key
sorted_data = sorted(data, key=lambda item: item[1])
print(sorted_data) # Output: [('banana', 1), ('apple', 2), ('cherry', 3)]
lambda item: item[1] is an anonymous function that takes one argument (item) and returns its second element (item[1]), which sorted() uses as the sorting key.