Skip to main content

Functional Programming in Python

Map, Filter, and Reduce

0:00
LearnStep 1/3

Functional Data Processing Tools

Python offers powerful functional programming tools for processing iterables: map, filter, and reduce. While these are staples in functional languages, Python often provides more 'Pythonic' alternatives like list comprehensions. Understanding both allows you to choose the right tool for the job.

1. Map

map(function, iterable) applies a function to every item in an iterable. It returns an iterator (in Python 3).

python

2. Filter

filter(function, iterable) constructs an iterator from elements of the iterable for which the function returns true.

python

3. Reduce

reduce(function, iterable) applies a function of two arguments cumulatively to the items of a sequence, reducing the sequence to a single value. It resides in the functools module.

python

4. The Case for Comprehensions

In modern Python, list comprehensions are often preferred over map and filter using lambda because they are more readable.

python

However, map and filter can be faster when using built-in functions (like str or int) rather than a custom lambda, and they are lazy by default (memory efficient).