Python Lambda Functions: Anonymous Functions, Map, Filter & Reduce

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().


1. Syntax and Basic Comparison: 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

2. Sorting with Lambdas (Custom Keys)

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']}")

3. Functional Programming Trio: map(), filter(), reduce()

A. map(function, iterable): Transform Each Element

celsius_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]

B. filter(function, iterable): Extract Matching Elements

numbers = [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]

C. functools.reduce(function, iterable): Cumulative Computation

from 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

Frequently Asked Questions (FAQ)

Can a lambda function contain multiple statements or assignments?

No. Python lambdas are syntactically restricted to a single expression. They cannot contain statements, loops (for/while), assignments, or raise statements. If you need multiple statements, you must define a regular function using def.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!