33. Transforming data with map, filter, reduce

Favor map, filter, and reduce to transform data. Your code will be more concise and better understood, as well as faster.

33.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

33.2. Do this

1from functools import reduce
2
3data = [i for i in range(10000000)]
4
5x = map(lambda val: val * 2, data)
6y = filter(lambda val: val % 2 == 0, x)
7z = reduce(lambda val1, val2: val1 + val2, y)