Programming Search⌘K

Conceptintro

Map, filter and reduce

Also called map, filter, reduce, fold, map-reduce, apply-to-all, accumulate, aggregate, select and where.

Map, filter and reduce are three higher-order functions on collections. Map changes each element, filter keeps the elements that pass a test, and reduce combines all elements into one value.

Applies to
core-languages

Idea

Map, filter and reduce are three functions that take a function and a collection. Each one replaces a common kind of loop.

  • Map "applies a given function to each element of a collection, e.g. a list or set, returning the results in a collection of the same type."1
  • Filter produces a new collection "containing exactly those elements of the original data structure for which a given predicate returns the Boolean value true."2
  • Reduce, also called fold, combines the elements into one value. "Fold is also termed as reduce, accumulate, aggregate, compress, or inject."3
from functools import reduce

nums = [1, 2, 3, 4, 5, 6]
print(list(map(lambda x: x * x, nums)))
print(list(filter(lambda x: x % 2 == 0, nums)))
print(reduce(lambda acc, x: acc + x, nums, 0))

evens = filter(lambda x: x % 2 == 0, nums)
squares = map(lambda x: x * x, evens)
print(reduce(lambda acc, x: acc + x, squares, 0))
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]
21
56

The last three lines join the three functions. Filter keeps 2, 4 and 6, map squares them to 4, 16 and 36, and reduce adds them to 56.

How it works

  1. Map. The function takes one element and returns one new element. The result has the same number of elements as the input. In Python, map will "Return an iterator that applies function to every item of iterable, yielding the results."4
  2. Filter. The function is a predicate: it takes one element and returns true or false. Python filter will "Construct an iterator from those elements of iterable for which function is true."4
  3. Reduce. The function takes two values: the result so far, often called the accumulator, and the next element. Python reduce will "Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value."5 An initial value starts the accumulator and is the result for an empty collection.
  4. Left and right folds. The order of the combination can change the result. "With a right fold, the sum would be parenthesized as 1 + (2 + (3 + (4 + 5))), whereas with a left fold it would be parenthesized as (((1 + 2) + 3) + 4) + 5."3 For an associative operation such as +, both give the same value3.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNative
GoIdiom
RustStandard library
KotlinNativeKotlin collections have the functions map, filter, reduce and fold, and a lambda gives the operation. No example file exists because kotlinc is not installed.
SQLIdiomThe SELECT list computes a value for each row, the WHERE clause keeps the rows that pass a test and aggregate functions such as SUM combine the rows. SQL has no function values, so these are clauses, not higher-order functions.
BashIdiom
PowerShellIdiomThe cmdlets ForEach-Object and Where-Object map and filter the objects in a pipeline, and a loop or Measure-Object combines them. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is a markup language and has no functions.
CSSDoes not applyCSS has no collections of values that a function can map, filter or reduce.
Regular expressionsDoes not applyA regular expression has no functions and no collections.
  • Python. The built-in functions map and filter, and functools.reduce45. Python 3 moved reduce out of the built-in functions. The release notes say: "Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."6
  • JavaScript. The array methods map, filter and reduce. map "creates a new array populated with the results of calling a provided function on every element in the calling array."7 filter "creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function."8 reduce runs "a user-supplied "reducer" callback function on each element of the array"9.
  • TypeScript. The same array methods as JavaScript, with types for the callbacks.
  • Java. Streams. The package has "functional-style operations on streams of elements, such as map-reduce transformations on collections."10 "A reduction operation (also called a fold) takes a sequence of input elements and combines them into a single summary result by repeated application of a combining operation"10.
  • C#. LINQ. The method Select is the select clause and Where is the where clause of a query expression11. Aggregate "Applies an accumulator function over a sequence."12
  • C++. The algorithms std::transform, std::copy_if and std::accumulate. std::transform "Applies the given function to the elements of the given source range(s), and stores the result in the destination range"13. "copy_if only copies the elements for which the predicate pred returns true"14. std::accumulate "Computes the sum of the given value init and all elements of the target range"15, or uses the operation op that the caller gives15.
  • Rust. The iterator methods map, filter and fold. map "Takes a closure and creates an iterator which calls that closure on each element."16 fold "Folds every element into an accumulator by applying an operation, returning the final result."16
  • Go. A for loop with a range clause. It "iterates through all entries of an array, slice, string or map"17. A program can write generic helper functions for map, filter and reduce.
  • C. A for loop over an array. A helper function can take a function pointer for the operation. See Function pointers and delegates.
  • Bash. A for loop over words. The loop will "execute commands once for each word in the resultant list, with name bound to the current word."18
PythonGitHub
from functools import reduce

nums = range(1, 7)
squares = list(map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums)))
print(*squares)
print(reduce(lambda acc, x: acc + x, squares, 0))
Output
4 16 36
56
  • Verdict: native. map and filter are built-in functions, and reduce is in the module functools. map and filter return iterators, so list keeps the result for the second use.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5, 6};
    std::vector<int> evens;
    std::copy_if(nums.begin(), nums.end(), std::back_inserter(evens),
                 [](int x) { return x % 2 == 0; });
    std::vector<int> squares(evens.size());
    std::transform(evens.begin(), evens.end(), squares.begin(),
                   [](int x) { return x * x; });
    for (std::size_t i = 0; i < squares.size(); ++i) {
        std::cout << (i ? " " : "") << squares[i];
    }
    std::cout << '\n';
    std::cout << std::accumulate(squares.begin(), squares.end(), 0) << '\n';
}
Output
4 16 36
56
  • Verdict: stdlib. std::copy_if filters, std::transform maps and std::accumulate reduces. Each one works on iterators, and the caller gives the place for the output.
JavaGitHub
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        List<Integer> squares = IntStream.rangeClosed(1, 6)
                .filter(x -> x % 2 == 0)
                .map(x -> x * x)
                .boxed()
                .toList();
        System.out.println(squares.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(" ")));
        System.out.println(squares.stream().reduce(0, Integer::sum));
    }
}
Output
4 16 36
56
  • Verdict: stdlib. The package java.util.stream has filter, map and reduce. The intermediate operations are lazy, and the terminal operation toList or reduce runs the pipeline.
#include <stdio.h>

static int is_even(int x) { return x % 2 == 0; }

static int square(int x) { return x * x; }

static int add(int a, int b) { return a + b; }

static size_t filter(const int *in, size_t n, int (*keep)(int), int *out) {
    size_t count = 0;
    for (size_t i = 0; i < n; i++) {
        if (keep(in[i])) {
            out[count++] = in[i];
        }
    }
    return count;
}

static void map(int *xs, size_t n, int (*f)(int)) {
    for (size_t i = 0; i < n; i++) {
        xs[i] = f(xs[i]);
    }
}

static int reduce(const int *xs, size_t n, int init, int (*f)(int, int)) {
    int acc = init;
    for (size_t i = 0; i < n; i++) {
        acc = f(acc, xs[i]);
    }
    return acc;
}

int main(void) {
    int nums[] = {1, 2, 3, 4, 5, 6};
    int buf[6];
    size_t n = filter(nums, 6, is_even, buf);
    map(buf, n, square);
    for (size_t i = 0; i < n; i++) {
        printf("%s%d", i ? " " : "", buf[i]);
    }
    printf("\n%d\n", reduce(buf, n, 0, add));
    return 0;
}
Output
4 16 36
56
  • Verdict: idiom. C has no map, filter or reduce. Helper functions take a function pointer and loop over an array. The caller gives the memory for the result.
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        var squares = Enumerable.Range(1, 6)
            .Where(x => x % 2 == 0)
            .Select(x => x * x)
            .ToList();
        Console.WriteLine(string.Join(" ", squares));
        Console.WriteLine(squares.Aggregate(0, (acc, x) => acc + x));
    }
}
Output
4 16 36
56
  • Verdict: stdlib. LINQ calls map Select, filter Where and reduce Aggregate.
JavaScriptGitHub
const nums = [1, 2, 3, 4, 5, 6];
const squares = nums.filter((x) => x % 2 === 0).map((x) => x * x);
console.log(squares.join(" "));
console.log(squares.reduce((acc, x) => acc + x, 0));
Output
4 16 36
56
  • Verdict: native. filter, map and reduce are methods of every array. Each call to filter or map makes a new array.
TypeScriptGitHub
const nums: number[] = [1, 2, 3, 4, 5, 6];
const squares: number[] = nums
  .filter((x) => x % 2 === 0)
  .map((x) => x * x);
console.log(squares.join(" "));
const total: number = squares.reduce((acc, x) => acc + x, 0);
console.log(total);
Output
4 16 36
56
  • Verdict: native. The array methods of JavaScript, with types. TypeScript gets the types of x and acc from the array and the initial value.
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func Map[T, U any](xs []T, f func(T) U) []U {
	out := make([]U, 0, len(xs))
	for _, x := range xs {
		out = append(out, f(x))
	}
	return out
}

func Filter[T any](xs []T, keep func(T) bool) []T {
	var out []T
	for _, x := range xs {
		if keep(x) {
			out = append(out, x)
		}
	}
	return out
}

func Reduce[T, A any](xs []T, init A, f func(A, T) A) A {
	acc := init
	for _, x := range xs {
		acc = f(acc, x)
	}
	return acc
}

func main() {
	nums := []int{1, 2, 3, 4, 5, 6}
	evens := Filter(nums, func(x int) bool { return x%2 == 0 })
	squares := Map(evens, func(x int) int { return x * x })
	fmt.Println(strings.Join(Map(squares, strconv.Itoa), " "))
	fmt.Println(Reduce(squares, 0, func(acc, x int) int { return acc + x }))
}
Output
4 16 36
56
  • Verdict: idiom. The Go standard library has no map, filter or reduce for slices. A program writes them as generic functions with a for loop and a range clause.
RustGitHub
fn main() {
    let squares: Vec<i32> = (1..=6).filter(|x| x % 2 == 0).map(|x| x * x).collect();
    let text: Vec<String> = squares.iter().map(|x| x.to_string()).collect();
    println!("{}", text.join(" "));
    println!("{}", squares.iter().fold(0, |acc, x| acc + x));
}
Output
4 16 36
56
  • Verdict: stdlib. The trait Iterator has filter, map and fold. The adapters are lazy, and collect runs them.
BashGitHub
is_even() { (($1 % 2 == 0)); }
square() { echo $(($1 * $1)); }
add() { echo $(($1 + $2)); }

squares=()
for x in 1 2 3 4 5 6; do
  if is_even "$x"; then
    squares+=("$(square "$x")")
  fi
done
echo "${squares[*]}"

total=0
for x in "${squares[@]}"; do
  total=$(add "$total" "$x")
done
echo "$total"
Output
4 16 36
56
  • Verdict: idiom. Bash has no map, filter or reduce, and functions are not values. A for loop calls a function for each word, an if keeps the words that pass the test, and a variable holds the running total.
  • Lazy or eager. Python map and filter return iterators4. In Java, "Intermediate operations are always lazy."10 Rust map is lazy too: "as map() is lazy, it is best used when you’re already working with other iterators."16 JavaScript array methods make a new array at once7.
  • Map fusion. Two maps in a row can become one map of the composed function. "this type of optimization is known as map fusion and is the functional analog of loop fusion."1 See Function composition.
  • Reduce without an initial value. JavaScript reduce and Rust reduce can start with the first element. In JavaScript, "If initialValue is not specified, accumulator is initialized to the first value in the array"9. Rust reduce returns an Option: "If the iterator is empty, returns None"16.
  • MapReduce. Dean and Ghemawat named a system for large clusters after these functions. Its abstraction was inspired by the map and reduce of Lisp and "many other functional languages"19.
  • Pipelines. A chain of map, filter and reduce calls is a pipeline. See Collection pipeline and Replace loop with pipeline. The task pages Map over a list and Reduce a list to a value show each step in all the languages.

Pitfalls

A Python map can be used only once

Python map and filter return iterators. "When no more data are available a StopIteration exception is raised instead. At this point, the iterator object is exhausted"20. A second loop over the same object sees nothing:

This code runs but gives a wrong answer on purpose.

squares = map(lambda x: x * x, [1, 2, 3])
print(sum(squares))
print(sum(squares))
Output
14
0

Call list(...) on the result when the program needs it more than once.

Reduce on an empty collection

Without an initial value, a reduce has no result for an empty collection. JavaScript reduce throws a TypeError, "Thrown if the array contains no elements and initialValue is not provided."9

This code runs but gives a wrong answer on purpose.

try {
  const total = [].reduce((acc, x) => acc + x);
  console.log(total);
} catch (e) {
  console.log(e.name);
}
Output
TypeError

Give the initial value: [].reduce((acc, x) => acc + x, 0) returns 0.

A lazy map that never runs

A lazy map does no work until a program reads its result. Rust says: "If you’re doing some sort of looping for a side effect, it’s considered more idiomatic to use for than map()."16 Use a for loop, or a method such as for_each, for side effects.

Cost

Each step makes one pass over the data. An eager map or filter also makes a new collection. Wikipedia says that two maps in a row are slower "because each map requires rebuilding an entire list from scratch"1. Lazy streams and iterators pass each element through all the steps and make no list in the middle1016. A loop that does all the work in one pass has the same cost as a lazy pipeline.

History

"The map function originated in functional programming languages."1 Lisp introduced a map function called maplist in 1959, "with slightly different versions already appearing in 1958."1 In 2004, Dean and Ghemawat described MapReduce, a library for computations on large clusters, and named it after the map and reduce of functional languages19.

References

  1. Map (higher-order function), Wikipedia, the introduction; Optimizations; Language comparison
  2. Filter (higher-order function), Wikipedia, the introduction; Example
  3. Fold (higher-order function), Wikipedia, the introduction; On lists; Evaluation order considerations
  4. Built-in Functions, The Python Standard Library, map; filter
  5. functools, The Python Standard Library, functools.reduce
  6. What's New In Python 3.0, Builtins
  7. Array.prototype.map(), MDN Web Docs, the introduction
  8. Array.prototype.filter(), MDN Web Docs, the introduction
  9. Array.prototype.reduce(), MDN Web Docs, the introduction; Parameters; Exceptions
  10. Package java.util.stream, Java SE 25 API, the package description; Stream operations and pipelines; Reduction operations
  11. Standard query operators overview, C# documentation, Query expression syntax for standard query operators
  12. Enumerable.Aggregate Method, .NET API, Overloads
  13. std::transform, C++ reference, cppreference.com, the description
  14. std::copy, std::copy_if, C++ reference, cppreference.com, the description
  15. std::accumulate, C++ reference, cppreference.com, the description
  16. Trait Iterator, The Rust Standard Library, map; filter; fold
  17. The Go Programming Language Specification, For statements with range clause
  18. Looping Constructs, Bash Reference Manual, for
  19. MapReduce, Simplified Data Processing on Large Clusters, Jeffrey Dean and Sanjay Ghemawat, OSDI 2004, 1 Introduction
  20. Glossary, The Python Documentation, iterator

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/BP6EDV/text.yaml