Skip to content

How to Use Map, Reduce, and Filter in Python

Learn how Python's map(), filter(), and reduce() functions work to transform, select, and aggregate data efficiently using functional programming techniques.

map(), reduce(), and filter() are three built-in Python functions that form the foundation of functional programming in the language. They allow you to transform, aggregate, and select data from iterables like lists, tuples, and sets, all without writing explicit loops.

These functions promote cleaner, more expressive code by separating what you want to do from how you iterate through data. In this guide, you will learn how each function works individually, see practical examples with lambda expressions, and discover how to combine all three for powerful data processing pipelines.

map(): Transform Every Element

The map() function applies a given function to every item in an iterable and returns an iterator of the results.

Syntax

map(function, iterable)
  • function: A function to apply to each element.
  • iterable: The sequence to transform (list, tuple, string, etc.).
  • Returns: A map object (iterator). Use list() to convert it to a list.

Example: Doubling Numbers

def double(n):
    return n * 2

numbers = [5, 6, 7, 8]
result = map(double, numbers)

print(list(result))

Output:

[10, 12, 14, 16]

Example: Using Lambda for Conciseness

numbers = [5, 6, 7, 8]
result = list(map(lambda n: n * 2, numbers))

print(result)

Output:

[10, 12, 14, 16]

Example: Converting Strings to Uppercase

words = ["hello", "world", "python"]
result = list(map(str.upper, words))

print(result)

Output:

['HELLO', 'WORLD', 'PYTHON']

Example: Multiple Iterables

map() can accept multiple iterables when the function takes multiple arguments:

a = [1, 2, 3]
b = [10, 20, 30]

result = list(map(lambda x, y: x + y, a, b))

print(result)

Output:

[11, 22, 33]

filter(): Select Elements That Match a Condition

The filter() function tests each element in an iterable against a function and returns only the elements for which the function returns True.

Syntax

filter(function, iterable)
  • function: A function that returns True or False for each element.
  • iterable: The sequence to filter.
  • Returns: A filter object (iterator) containing only the elements that passed the test.

Example: Filtering Even Numbers

def is_even(n):
    return n % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(filter(is_even, numbers))

print(result)

Output:

[2, 4, 6, 8, 10]

Example: Using Lambda to Filter

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = list(filter(lambda n: n % 2 == 0, numbers))

print(result)

Output:

[2, 4, 6, 8, 10]

Example: Filtering Non-Empty Strings

words = ["hello", "", "world", "", "python", ""]
result = list(filter(None, words))

print(result)

Output:

['hello', 'world', 'python']

reduce(): Aggregate Into a Single Value

The reduce() function applies a function of two arguments cumulatively to the items of an iterable, reducing it to a single value. Unlike map() and filter(), reduce() is not a built-in; it must be imported from the functools module.

Syntax

from functools import reduce

reduce(function, iterable[, initial])
  • function: A function that takes two arguments (accumulator and current element).
  • iterable: The sequence to reduce.
  • initial (optional): A starting value for the accumulator.
  • Returns: A single accumulated value.

Example: Product of All Elements

from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)

print(product)

Output:

24

How it works step by step:

Step Accumulator (x) Current (y) Result
1 1 2 2
2 2 3 6
3 6 4 24

Example: Sum With an Initial Value

from functools import reduce

numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers, 100)

print(total)

Output:

110

The initial value 100 is used as the first accumulator value, so the reduction starts with 100 + 1 = 101.

Example: Finding the Maximum Value

from functools import reduce

numbers = [45, 12, 78, 34, 56]
maximum = reduce(lambda x, y: x if x > y else y, numbers)

print(maximum)

Output:

78

Combining map(), filter(), and reduce()

The real power of these functions emerges when you chain them together to build data processing pipelines.

Example 1: Sum of Squares of Even Numbers

from functools import reduce

numbers = [1, 2, 3, 4, 5, 6]

evens = filter(lambda x: x % 2 == 0, numbers)

squares = map(lambda x: x ** 2, evens)

result = reduce(lambda x, y: x + y, squares)

print(result)

Output:

56

Pipeline breakdown:

[1, 2, 3, 4, 5, 6]
    -> filter(even)  -> [2, 4, 6]
    -> map(square)   -> [4, 16, 36]
    -> reduce(sum)   -> 56

Example 2: Product of Positive Numbers

from functools import reduce

numbers = [-3, -1, 2, 4, -2, 5]

result = reduce(
    lambda x, y: x * y,
    filter(lambda x: x > 0, numbers)
)

print(result)

Output:

40

Pipeline: [-3, -1, 2, 4, -2, 5] -> filter positives -> [2, 4, 5] -> multiply -> 2 × 4 × 5 = 40

Example 3: Total Length of Words Containing Vowels

from functools import reduce

words = ["sky", "apple", "tree", "gym", "orange"]

result = reduce(
    lambda a, b: a + b,
    map(
        lambda w: len(w),
        filter(
            lambda w: any(v in w for v in 'aeiou'),
            words
        )
    )
)

print(result)

Output:

15

Pipeline:

["sky", "apple", "tree", "gym", "orange"]
    -> filter(has vowels) -> ["apple", "tree", "orange"]
    -> map(len)           -> [5, 4, 6]
    -> reduce(sum)        -> 15

map() / filter() vs. List Comprehensions

Python also supports list comprehensions, which can replace map() and filter() in many cases:

numbers = [1, 2, 3, 4, 5, 6]

result = list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers)))

result = [x ** 2 for x in numbers if x % 2 == 0]

print(result)

Output:

[4, 16, 36]
Approach Readability Performance Best For
map() / filter() Moderate Slightly faster for large datasets (lazy evaluation) Functional style, passing functions dynamically
List comprehension High Similar Pythonic, straightforward transformations
reduce() Lower Good Aggregation with no built-in equivalent

Quick Reference

Function Purpose Returns Module
map(fn, iterable) Apply fn to every element Iterator of transformed values Built-in
filter(fn, iterable) Keep elements where fn returns True Iterator of filtered values Built-in
reduce(fn, iterable) Accumulate elements into a single value Single value functools

Conclusion

map(), filter(), and reduce() are essential tools for functional programming in Python.

  • map() transforms every element in an iterable
  • filter() selects elements that match a condition
  • reduce() aggregates an entire iterable into a single value.

When chained together, they form powerful, readable data processing pipelines: filtering data, transforming it, and reducing it to a final result, all without writing a single loop. For simple cases, list comprehensions are often more Pythonic, but these three functions shine when passing functions dynamically or processing large datasets lazily.

Navigation