Map and Filter
Now we’re going to see some tools that solve the same problem as list comprehensions, but which are much less commonly used in Python.
Lambda
First let’s take a look at lambda functions.
A lambda function is a single-statement function that has inputs and an output and is free of side effects (it doesn’t do anything besides return something).
>>> is_odd = lambda x: x % 2 == 1
>>> is_odd(5)
True
>>> is_odd(4)
False
Lambda functions are functions, but they’re a special, more limited, type of function:
>>> is_odd
<function <lambda> at 0x7f0a6a885158>
>>> type(is_odd)
<class 'function'>
Map
The map built-in function in Python allows us to loop over an iterable, change each item, and produce another iterable from these changed items.
>>> numbers = [1, 2, 3, 4]
>>> double = lambda x: x * 2
>>> doubled_numbers = map(double, numbers)
>>> doubled_numbers
<map object at 0x7f0a6891fe10>
>>> list(doubled_numbers)
[2, 4, 6, 8]
We could also write the double lambda and the map call all on one line:
>>> doubled_numbers = map(lambda x: x * 2, numbers)
>>> list(doubled_numbers)
[2, 4, 6, 8]
The reason we don’t use map often, is that it solves the same problem as a basic list comprehension:
>>> doubled_numbers = [x * 2 for x in numbers]
>>> doubled_numbers
[2, 4, 6, 8]
Filter
The filter built-in function allows us to filter an iterable, discarding values that do not match a given predicate function.
>>> is_odd = lambda x: x % 2 == 1
>>> odd_numbers = filter(is_odd, numbers)
>>> odd_numbers
<filter object at 0x7f0a6891fc88>
>>> list(odd_numbers)
[1, 3]
This is basically the same as the optional condition clause in a list comprehension:
>>> [x for x in numbers if is_odd(x)]
[1, 3]
If we combine map and filter we’d have the same functionality as a list comprehension:
>>> is_odd = lambda x: x % 2 == 1
>>> square = lambda x: x ** 2
>>> squares_of_odds = list(map(square, filter(is_odd, numbers)))
>>> squares_of_odds
[1, 9]
>>> squares_of_odds = [square(x) for x in numbers if is_odd(x)]
>>> squares_of_odds
[1, 9]
So if you ever see code that uses filter or map or if you’re ever tempted to use a lambda function, think about the alternatives. It might be possible to use list comprehensions to make your code more readable.