6. Transforming data with map, filter, reduce
In Python, comprehensions and generator expressions are usually easier to read than chaining map, filter, and reduce. Reach for the functional tools when they are clearly the best fit, not by default.
Most Python readers parse comprehension syntax faster because the transformation and filter live next to the resulting collection shape. That reduces the cognitive overhead of jumping between multiple function calls and anonymous lambdas.
6.1. Don’t do this
1data = [i for i in range(10000000)]
2
3x = []
4for val in data:
5 x.append(val * 2)
6
7y = []
8for val in x:
9 if val % 2 == 0:
10 y.append(val)
11
12z = 0
13for val in y:
14 z = z + val
6.2. Do this
1data = [i for i in range(10000000)]
2
3z = sum(val * 2 for val in data if (val * 2) % 2 == 0)