Lambda, map, filter, reduce
Tiny anonymous functions and the functional trio for reshaping data
lambda is a small, unnamed function you write in a single line. map, filter and reduce are higher-order functions — they take another function and apply it across a whole sequence to transform it, select from it, or fold it into one value.
- write a
lambdaand know when it is (and is not) worth it, - transform every item of a sequence with
map, - keep only the items you want with
filter, - fold a sequence into a single value with
functools.reduce, - weigh the readability trade-off against a comprehension or a plain loop.
1. What is a lambda?
A lambda is an anonymous function: a function with no name, defined inline where you need it. The syntax is the keyword lambda, then parameters, a colon, and one expression whose value is returned automatically.
double = lambda x: x * 2
print(double(5)) # 10
That lambda is exactly equivalent to this named function:
def double(x):
return x * 2
A lambda may take several parameters, separated by commas:
add = lambda a, b: a + b
print(add(3, 4)) # 7
return keyword (the result is returned for you), and you cannot put assignments, loops, or multiple statements inside. When you need those, use def.2. map: transform every item
map(function, iterable) applies function to each item and yields the results. In Python 3 it returns a lazy iterator (a map object), so you usually wrap it in list() to see the values.
nums = [1, 2, 3, 4]
squares = list(map(lambda n: n * n, nums))
print(squares) # [1, 4, 9, 16]
The function does not have to be a lambda — any callable works, including built-ins:
prices = ["10", "25", "7"]
as_int = list(map(int, prices))
print(as_int) # [10, 25, 7]
map can walk several iterables at once; the function then receives one argument from each:
a = [1, 2, 3]
b = [10, 20, 30]
sums = list(map(lambda x, y: x + y, a, b))
print(sums) # [11, 22, 33]