In Python, a lambda function is a small, anonymous function defined without a name using the lambda keyword. While standard functions are declared using def with formal function names and multi-line bodies, lambdas are designed for quick, throwaway single-expression operations—especially when passing callback functions to map(), filter(), and sort().
def vs lambda# Standard def function:
def square(x):
return x ** 2
# Equivalent lambda function:
square_lambda = lambda x: x ** 2
print("Standard:", square(6)) # 36
print("Lambda: ", square_lambda(6)) # 36
Lambda with multiple arguments:
multiply = lambda a, b, c: a * b * c
print("Product:", multiply(2, 3, 4)) # 24
The most common real-world use of lambdas is providing custom sorting criteria to sort() and sorted():
students = [
{"name": "Rohan", "gpa": 8.4},
{"name": "Ananya", "gpa": 9.8},
{"name": "Vikram", "gpa": 7.9}
]
# Sort students in descending order of GPA using lambda:
students.sort(key=lambda s: s["gpa"], reverse=True)
for s in students:
print(f"{s['name']}: {s['gpa']}")
map(), filter(), reduce()map(function, iterable): Transform Each Elementcelsius_temps = [0, 20, 35, 100]
# Convert to Fahrenheit: (C * 9/5) + 32
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius_temps))
print("Fahrenheit:", fahrenheit) # [32.0, 68.0, 95.0, 212.0]
filter(function, iterable): Extract Matching Elementsnumbers = [12, 45, 68, 73, 84, 91, 102]
# Filter out only numbers divisible by 4:
div_by_4 = list(filter(lambda x: x % 4 == 0, numbers))
print("Divisible by 4:", div_by_4) # [12, 68, 84]
functools.reduce(function, iterable): Cumulative Computationfrom functools import reduce
# Calculate Factorial / Cumulative Product of [1, 2, 3, 4, 5]:
nums = [1, 2, 3, 4, 5]
product = reduce(lambda acc, item: acc * item, nums)
print("Product of list:", product) # 120
for/while), assignments, or raise statements. If you need multiple statements, you must define a regular function using def.