Python lambda functions and when to use them
lambda syntax, lambda limitations, sort with key, map, filter, reduce, lambda vs named function
Lambda Functions
A lambda is a single-expression anonymous function. It returns the expression's value implicitly. Use it for short, throwaway functions โ not for anything requiring multiple lines or a docstring.
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
With sort, map, filter
people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
# sort by age
people.sort(key=lambda p: p[1])
print(people) # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
# map: apply function to every element
nums = [1, 2, 3, 4]
doubled = list(map(lambda x: x * 2, nums))
# [2, 4, 6, 8]
# filter: keep elements where function is True
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4]
When NOT to Use Lambda
If you find yourself writing a complex lambda or assigning it to a variable and reusing it, write a named function instead. PEP 8 explicitly discourages assigning lambdas to names. Prefer list comprehensions over map/filter with lambdas for clarity.
Lambdas are most appropriate as inline one-off callbacks โ the key= argument in sorting, the default= argument in certain APIs, or simple transformations passed to map and filter. If you need the logic more than once, give it a name. The functools.reduce function takes a binary function and folds a sequence into a single value โ useful occasionally, but explicit loops are usually clearer. Python emphasises readability over cleverness; a three-line function with a descriptive name beats a one-liner nobody can parse on first read.
