Using reduce in Python.

Python has a built in operator called reduce. This is just another name for what a functional programmer would called a fold. They’re really useful, but you don’t know so until you actually need one. The easiest example to understand is listed below and is the same example provided on Python’s documentation.

lon = [1, 2, 3, 4, 5]
print reduce(lambda acc, v: acc+v, lon)

Think of acc as the ‘accumulator’. This is the value that is threaded into each add operation, literally accumulating whatever your function is doing. They’re fun an make your code readable and concise.

This entry was posted in Programming and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.