Functional Programming In Python - Filtering Lists Using filter()
Consider this list,
foo = range(1,100)
Now I have to find only multiples of 5 in foo.
Without FP, You (or I) would probably do something like this:
>>> >>> bar = [] >>> for x in foo: ... if x%5 == 0: ... bar.append(x) ... >>> print bar [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] >>>
But with FP, the solution is quite elegant, here's how it can be done:
>>> def f(x): return x%5 == 0 ... >>> filter(f, foo) [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
filter(function, list) takes the list and applies the function on each item of the list.
From the docs:
filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true.












