Lambda Functions
A lambda function is a small, anonymous (has no name) inline function defined with the lambda keyword. They are restricted to a single expression, the result of which is implicitly returned.
Syntax
lambda arguments: expression
Example 1: Simple Addition
python
Standard function
def add(a, b): return a + b
Equivalent Lambda function
add_lambda = lambda a, b: a + b
print(add_lambda(5, 3)) # Output: 8
Example 2: Lambdas as Function Arguments
The primary use of lambda functions is when you need a simple, disposable function as an argument to a higher-order function (like sorted(), map(), or filter()).
Sorting based on a specific key
We want to sort a list of tuples by the second element (index 1).
python students = [('Alice', 88), ('Bob', 95), ('Charlie', 79)]
Sort by score (the second element of the tuple)
The lambda function tells sorted() which value to use for comparison
sorted_students = sorted(students, key=lambda student: student[1])
print(sorted_students)