Combining Functions

Learn how and when to combine functions, such as "map", "filter", and "zip", in a single expression.

We'll cover the following...

It is often useful to combine the functions, map, filter, and zip in a single expression. Here are some examples.

map and filter

map and filter work well together. Here is an example where we are using map to take the square root of a series of numbers. Since the square root function doesn’t accept negative input, we use filter to remove any negative values first. Here is the code:

Press + to interact
import math
k = [1, 4, -2, 16, -3, 36, -1]
f = filter(lambda x: x>=0, k)
m = map(math.sqrt, f)
print(list(m)) #[1.0, 2.0, 4.0, 6.0]

Of course, the output data has fewer elements than the input data because some negative values have been filtered out. We have shown map and filter as two separate lines of code, but it would be quite normal to combine them, as shown below.

Press + to interact
m = map(math.sqrt, filter(lambda x: x>=0, k))

Pipelines

We looked at lazy evaluation earlier in this chapter. When we chain two or more functions that use lazy evaluation, we create a pipeline. In this section, we will see how this works.

We are going to use map and filter ...