Python Functional Programming

python

https://github.com/kachayev/fn.py

filter(function, sequence) returns a sequence consisting of those items from the sequence for which function(item) is true. If sequence is a string or tuple, the result will be of the same type; otherwise, it is always a list.

map(function, sequence) calls function(item) for each of the sequence’s items and returns a list of the return values.

More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). For example:

``````>>> seq = range(8)
>>> def add(x, y): return x+y
...
[0, 2, 4, 6, 8, 10, 12, 14]```
```

reduce(function, sequence) returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:

``````>>> def add(x,y): return x+y
...
55```
```

If there’s only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.

A third argument can be passed to indicate the starting value. In this case the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, then to the result and the next item, and so on. For example:

``````>>> def sum(seq):
...
>>> sum(range(1, 11))
55
>>> sum([])
0```
```

See the following sections:

List Comprehensions
Nested List Comprehensions

page revision: 3, last edited: 01 Aug 2016 21:01