Lambda Functions & Built-in Higher-Order Functions
Python provides powerful tools for functional-style programming without needing to import anything extra. Lambda functions, combined with built-ins like map(), filter(), sorted(), and zip(), let you write concise, expressive data transformations.
Lambda Functions
A lambda is an anonymous function โ a function defined without a name. It's useful when you need a short function for a single use and don't want to define a full def block.
Syntax
The body is a single expression that is automatically returned. No return keyword, no multiple statements.
Lambdas are most powerful when passed directly to another function rather than assigned to a variable. When you assign a lambda to a name, a regular def is usually cleaner.
map() โ Transform Every Element
map(function, iterable) applies a function to every element of an iterable and returns a lazy iterator.
map() is lazy โ it only computes values when you iterate over them, which saves memory for large datasets. Wrap in list() only when you need all values at once.
filter() โ Keep Only Matching Elements
filter(function, iterable) keeps only elements for which the function returns True.
sorted() with key=
sorted(iterable, key=None, reverse=False) returns a new sorted list. The key parameter is a function applied to each element to determine its sort order.
reversed() โ Reverse Any Sequence
reversed() returns a lazy iterator over the sequence in reverse order.
zip() โ Pair Elements Together
zip(*iterables) pairs up elements from multiple iterables into tuples. Stops at the shortest.
enumerate() โ Index + Value Together
enumerate(iterable, start=0) yields (index, value) pairs.
any() and all()
any(iterable) returns True if at least one element is truthy. all(iterable) returns True if every element is truthy.
sum(), min(), max() with key=
These built-ins also accept a key= argument:
Combining These Tools
The real power comes from chaining these functions together:
When to use map()/filter() vs list comprehensions: both are valid. Comprehensions are often more readable for simple cases. map()/filter() are more functional-style and can be composed more easily in pipelines.
Knowledge Check
What does `list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))` return?
Which built-in function pairs elements from multiple iterables into tuples?
What does `sorted(['banana', 'apple', 'kiwi'], key=len)` return?