Lambda, Map, Filter & Reduce
Lambda functions are anonymous one-liner functions. Combined with map(), filter(), and reduce(), they enable powerful functional programming patterns in Python. This section explores their formal definitions, behavior, and return values.
📋 Table of Contents
1 · Lambda Functions
In computer science, a lambda abstraction is the definition of an anonymous function. In Python, the lambda keyword creates a function object that can be used anywhere a function is expected, but without a formal name (unless assigned to a variable).
"A lambda is an expression that creates a function object, but it is limited to a single expression. It is often called an 'anonymous function' because it doesn't require a def statement or a name." — Learning Python, Mark Lutz
# Anonymous function to square a number square = lambda x: x ** 2 print(square(5)) # Output: 25 # Immediately Invoked Function Expression (IIFE) print((lambda x, y: x + y)(10, 20)) # Output: 30
A lambda expression returns a function object at runtime. This object behaves exactly like a function defined with def, but it is restricted to a single expression whose result is the function's return value.
2 · map(): Functional Transformation
The map(function, iterable) function applies a given function to every item of an iterable (list, tuple, etc.) and returns a map object.
In modern Python, list comprehensions are often preferred over map() for readability, but map() is highly efficient when using built-in functions.
names = ["alice", "bob", "charlie"] upper_names = map(str.upper, names) print(list(upper_names)) # ['ALICE', 'BOB', 'CHARLIE']
In Python 3.x, map() returns an iterator (specifically a map object). It is lazy, meaning it doesn't compute the values until you iterate over it (e.g., using list() or a for loop).
3 · filter(): Boolean Selection
filter(function, iterable) constructs an iterator from those elements of an iterable for which the function returns true.
numbers = [1, 2, 3, 4, 5, 6] evens = filter(lambda x: x % 2 == 0, numbers) print(list(evens)) # [2, 4, 6]
Similar to map(), filter() returns a filter object (an iterator). Elements are processed only when requested, saving memory for large datasets.