xsyszs314map2filtertotalreduce1from functools import reduce2xs = [3, 1, 4, 2]3def double(x): return x * 24ys = list(map(double, xs))5zs = list(filter(lambda y: y > 4, ys))6total = reduce(lambda a, b: a + b, zs)7t = 08for y in zs: t += ydoubletdouble(3) == 6 ✓
Code card: the program; the highlighted line is the one being explainedFunction blocks: map, filter and reduce, each holding the function it was givenLists: one cell per value; every block fills a new listt: the loop's single variable, overwritten on every passEach step lights the line of code and the parts it is about. In the pipeline at the back, values ride their lanes from one list to the next and pass through a function block on the way: map doubles each value, filter keeps those above 4, reduce adds them up. Every block makes a new list; xs is never changed. The loop in lines 7 and 8 reaches the same 14 by overwriting one variable, t, on every pass. A Python list is mutable: xs[0] = 9 would change it in place. Functional style simply never does that. A tuple such as (3, 1, 4, 2) is immutable: Python refuses to change it.

Functions as values

  1. Line 3 defines double. Give it 3 and it returns 6, every time. It only reads its input and changes nothing outside itself (no side effects): no printing, no global variables, no editing of lists. That is a pure function.

The pipeline

Why it helps

Try it in the Python prompt

;; step 1/10 · line 3: def double(x): return x * 2
>>> def double(x): return x * 2
>>> double(3)
6
>>> double(3)      # same input, same output
6

In Python 3, map and filter return lazy iterators that make each value only when asked; wrapping them in list(...) runs them and stores the results in a new list. reduce lives in the functools module, which is why line 1 imports it. For adding numbers, the built-in sum(zs) does the same job and is easier to read.