Programming Search⌘K

Conceptcore

Comprehension

Also called list comprehension, set comprehension, dict comprehension, dictionary comprehension, generator expression, for comprehension, query expression, query syntax, set-builder notation, for-yield.

A comprehension is an expression that builds a collection from a source, an optional filter and an expression for each item. It does the work of a loop that appends to a new list.

Applies to
core-languages

Idea

A program often makes a new collection from an old one: it takes each item, keeps some of them and computes a new value from each item that it keeps. A loop can do this work. The loop makes an empty list, reads the source, tests each item and appends the result. A comprehension writes the same work as one expression. The Python tutorial says: "List comprehensions provide a concise way to create lists"1.

A comprehension has three parts:

  • a source, the collection or iterator that gives the items;
  • an optional filter, a condition that each item must pass;
  • an expression, which gives the value to put in the result for each item that passes.

The form comes from mathematics. Set-builder notation writes a set as { 2n | n ∈ ℕ, n < 5 }, which is the set of all 2n where n is a natural number less than 5. Wikipedia defines it as "a notation for specifying a set by a property that characterizes its members"2. A comprehension in a programming language uses the same shape, but its source is a finite collection or a stream, so a computer can build the result.

words = ["apple", "fig", "banana", "kiwi", "cherry"]

# A list comprehension: an expression, a source and a filter.
lengths = [len(w) for w in words if len(w) > 3]
print(lengths)

# The same list, built with a loop.
result = []
for w in words:
    if len(w) > 3:
        result.append(len(w))
print(result == lengths)

# Set and dict comprehensions use braces.
print(sorted({w[0] for w in words}))
print({w: len(w) for w in words if "i" in w})

# Two for clauses nest like two loops. The first for clause is the outer loop.
print([(x, y) for x in range(1, 3) for y in "ab"])

# A generator expression makes the items one at a time, when they are needed.
squares = (n * n for n in range(1_000_000))
print(next(squares), next(squares), sum(n * n for n in range(4)))

# The loop variable does not leak out of the comprehension.
w = "outer"
copy = [w for w in words]
print(w)
Output
[5, 6, 4, 6]
True
['a', 'b', 'c', 'f', 'k']
{'fig': 3, 'kiwi': 4}
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
0 1 14
outer

The first comprehension and the loop give the same list. The braces make a set or a dict. Two for clauses give all the pairs, in the order of two nested loops. The generator expression does not make a million squares. It makes each square when next or sum asks for it. After the comprehension, w still has its old value.

How it works

A comprehension is a short way to write a loop. The Python reference describes the parts: "In its simplest form, a comprehension consists of a single expression followed by a for clause"3, and the tutorial gives the full form: "A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it"1.

To read a comprehension with many clauses, write each clause on its own line in the same order, as a loop or an if inside the clause before it, and put the expression at the innermost level with an append. So [x for row in m if row for x in row] is the same as:

result = []
for row in m:
    if row:
        for x in row:
            result.append(x)

The expression comes first in the text, but it runs last, once for each set of values that the clauses produce.

The same idea has other names in other languages:

  • A map and a filter. PEP 202 gives the reason for list comprehensions in Python: "List comprehensions provide a more concise way to create lists in situations where map() and filter() and/or nested loops would currently be used"4. A comprehension with one for and one if is a filter followed by a map. A comprehension with two for clauses is a flat map. The Haskell report defines a list comprehension by a translation into simpler expressions, and the translation uses concatMap5. See map over a list, filter a list and flatten a nested list.
  • Generators and qualifiers. The Haskell report says: "A list comprehension has the form [ e | q1, …, qn ],n ≥ 1, where the qi qualifiers are either generators", boolean guards or local bindings. It also gives the order of the work: "Such a list comprehension returns the list of elements produced by evaluating e in the successive environments created by the nested, depth-first evaluation of the generators in the qualifier list"5. Erlang uses the same words. Its guide reads [X || X <:- [1,2,a,3,4,b,5,6], X > 3] like set-builder notation: "The list of X such that X is taken from the list [1,2,a,...] and X is greater than 3"6.
  • Other result types. The result need not be a list. Python has set comprehensions and dict comprehensions. PEP 274 calls the second form "the “dictionary comprehension” or “dict comprehension” for short"7. A dict comprehension has a key expression and a value expression.
  • Lazy results. A generator expression has the same syntax in parentheses, but it gives an iterator, not a list. PEP 289 describes "generator expressions as a high performance, memory efficient generalization of list comprehensions"8. The Python reference says that "a generator expression evaluates to a generator iterator which yields the same values as the corresponding list comprehension"3.

Scope. In Python, the names in the for clauses belong to the comprehension: "the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don’t “leak” into the enclosing scope"3. There are two exceptions. First, "The iterable expression in the leftmost for clause is evaluated directly in the enclosing scope and then passed as an argument to the implicitly nested scope"3, so the first source is evaluated at once, also for a generator expression. Second, an assignment expression with := inside a comprehension "binds the target in the containing scope"9. PEP 572 gives a reason: the name can keep a witness for any() or a counterexample for all().

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaStandard library
CIdiom
C#Native
JavaScriptIdiom
TypeScriptIdiomTypeScript has no comprehension syntax. It uses the JavaScript methods filter, map and flatMap, and the compiler checks the types of the items and the result. No example file exists.
GoIdiom
RustStandard library
KotlinStandard libraryKotlin has no comprehension syntax. The standard library has filter, map, flatMap and associate on collections, and sequence builds a lazy chain. No example file exists because kotlinc is not installed.
SQLNativeA SELECT statement has the same three parts as a comprehension. FROM names the source, WHERE is the filter and the select list gives the expression for each row. No example file exists.
BashIdiomBash has no comprehension. A for loop over words with a test appends to an array, or a pipeline of commands such as grep and sed filters and changes lines. No example file exists.
PowerShellIdiomA pipeline with Where-Object for the filter and ForEach-Object for the expression gives a new array. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. It has no expressions that build collections.
CSSDoes not applyCSS has no expressions that build collections from other collections.
Regular expressionsDoes not applyA regular expression matches text. It does not build collections.
Language Verdict Mechanism
Python native list [e for x in s if c], set {e for ...}, dict {k: v for ...} and generator (e for ...) comprehensions
JavaScript idiom no comprehension syntax; filter, map, flatMap, Array.from and the lazy iterator helpers
TypeScript idiom the JavaScript methods, with types for the items and the result
Java stdlib streams: filter, map, flatMap, then toList or a Collector
Kotlin stdlib filter, map, flatMap and associate on collections; sequence for lazy work
C# native LINQ query syntax from x in s where c select e; the compiler turns it into Where and Select calls
Go idiom no comprehension syntax; a for loop with append, or an iterator function in a range loop
Rust stdlib iterator adapters filter, map and flat_map, then collect into the type that the program names
C idiom a for loop that writes into an array and counts the items
C++ stdlib range views std::views::filter and std::views::transform, joined with |
Bash idiom a for loop over words with a test, or a pipeline of commands such as grep and sed
PowerShell idiom a pipeline with Where-Object and ForEach-Object
SQL native SELECT e FROM t WHERE c has a source, a filter and an expression for each row
Regex n/a a pattern matches text and does not build collections
HTML n/a markup does not build collections
CSS n/a the style rules do not build collections

A comprehension is syntax, so only some languages have it. Other languages give the same result with higher-order functions, and the chain of calls has the same three parts. Many languages that have comprehensions also define them as a translation into such calls. C# says: "The C# compiler translates query syntax into method calls"10. Scala says: "Comprehensions have the form for (enumerators) yield e" and "A comprehension evaluates the body e for each binding generated by the enumerators and returns a sequence of these values"11. Elixir says: "Comprehensions are syntactic sugar for such constructs" and "A comprehension is made of three parts: generators, filters, and collectables"12.

The example files show these forms. Python shows a flatten, a nested comprehension, the difference between a filter and a conditional expression, an assignment expression that leaves the comprehension, and the order in which a generator expression evaluates its sources. JavaScript shows filter and map, a Set, Object.fromEntries, flatMap and the lazy iterator helpers. Java shows a stream with toList, toMap, flatMap and the laziness of limit. C# shows query syntax, two from clauses, the same query in method syntax and a deferred query. Go shows loops, a set made from a map and an iterator function. Rust shows collect into a vector, a set and a map, flat_map and the laziness of take. C shows the loop that a comprehension replaces. C++ shows a view pipeline and that a view runs only when the program reads it.

PythonGitHub
matrix = [[1, 2, 3], [4, 5, 6]]

# Flatten: the for clauses read from left to right, like nested loops.
print([x for row in matrix for x in row])

# A comprehension inside a comprehension makes a nested list.
print([[row[i] for row in matrix] for i in range(3)])

# An "if" after the "for" is a filter. An "a if c else b" before the "for" is part of the expression.
nums = range(-2, 3)
print([n for n in nums if n > 0])
print([n if n > 0 else 0 for n in nums])

# An assignment expression in a comprehension binds its name in the enclosing scope.
data = [3, 8, 1, 9]
if any((big := n) > 5 for n in data):
    print("first big value:", big)


def source(name, items):
    print("evaluate", name)
    return items


# The leftmost source is evaluated at once. The other parts run when the generator runs.
gen = (x + y for x in source("outer", [1, 2]) for y in source("inner", [10]))
print("generator made")
print(list(gen))

# A generator can be used only once.
print(list(gen))
Output
[1, 2, 3, 4, 5, 6]
[[1, 4], [2, 5], [3, 6]]
[1, 2]
[0, 0, 0, 1, 2]
first big value: 8
evaluate outer
generator made
evaluate inner
evaluate inner
[11, 12]
[]
  • Verdict: native. Python has list, set and dict comprehensions and generator expressions. This file shows a flatten and a nested comprehension, the difference between a filter and a conditional expression, an assignment expression that binds a name outside the comprehension, and a generator expression that evaluates its leftmost source at once and its other parts later. The second list() call gives an empty list because a generator can be read only once.
#include <cctype>
#include <iostream>
#include <map>
#include <ranges>
#include <set>
#include <string>
#include <vector>

template <class R>
void print(R&& r) {
    const char* sep = "";
    for (auto&& x : r) {
        std::cout << sep << x;
        sep = " ";
    }
    std::cout << '\n';
}

int main() {
    std::vector<std::string> words{"apple", "fig", "banana", "kiwi", "cherry"};

    // A view pipeline: a source, a filter and a transform.
    auto lengths = words
        | std::views::filter([](const std::string& w) { return w.size() > 3; })
        | std::views::transform([](const std::string& w) { return w.size(); });
    print(lengths);

    // The iterator pair constructors build a set or a vector from a view.
    auto heads = words | std::views::transform([](const std::string& w) { return w[0]; });
    std::set<char> firsts(heads.begin(), heads.end());
    print(firsts);

    // A map is filled with a loop over a filtered view.
    std::map<std::string, std::size_t> withI;
    for (const auto& w : words | std::views::filter([](const std::string& w) { return w.contains('i'); })) {
        withI[w] = w.size();
    }
    for (const auto& [k, v] : withI) {
        std::cout << k << '=' << v << (k == withI.rbegin()->first ? '\n' : ' ');
    }

    // Views are lazy: the transform runs only when the items are read.
    int calls = 0;
    auto upper = words
        | std::views::transform([&calls](const std::string& w) {
              ++calls;
              std::string u = w;
              for (auto& c : u) {
                  c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
              }
              return u;
          })
        | std::views::take(2);
    std::cout << "calls before reading: " << calls << '\n';
    std::vector<std::string> firstTwo(upper.begin(), upper.end());
    print(firstTwo);
    std::cout << "calls after reading: " << calls << '\n';
}
Output
5 6 4 6
a b c f k
fig=3 kiwi=4
calls before reading: 0
APPLE FIG
calls after reading: 2
  • Verdict: stdlib. C++ has no comprehension syntax, but a view pipeline with std::views::filter and std::views::transform has the same parts. The iterator pair constructors build a std::set or a std::vector from a view. A view is lazy, so the transform has run 0 times when the program makes the view, and 2 times after the program reads the two items that std::views::take(2) gives.
JavaGitHub
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> words = List.of("apple", "fig", "banana", "kiwi", "cherry");

        // A stream does the work of a comprehension: a source, a filter and a map.
        List<Integer> lengths = words.stream().filter(w -> w.length() > 3).map(String::length).toList();
        System.out.println(lengths);

        // A collector builds a set or a map instead of a list.
        Set<Character> firsts = words.stream()
                .map(w -> w.charAt(0))
                .collect(Collectors.toCollection(TreeSet::new));
        System.out.println(firsts);
        Map<String, Integer> withI = words.stream()
                .filter(w -> w.contains("i"))
                .collect(Collectors.toMap(w -> w, String::length, (a, b) -> a, TreeMap::new));
        System.out.println(withI);

        // flatMap does the work of two for clauses.
        List<String> pairs = IntStream.rangeClosed(1, 2).boxed()
                .flatMap(x -> Stream.of("a", "b").map(y -> x + y))
                .toList();
        System.out.println(pairs);

        // A stream is lazy: map runs only for the items that limit needs.
        int[] calls = {0};
        List<String> firstTwo = words.stream()
                .map(w -> {
                    calls[0]++;
                    return w.toUpperCase();
                })
                .limit(2)
                .toList();
        System.out.println(firstTwo + " " + calls[0]);
    }
}
Output
[5, 6, 4, 6]
[a, b, c, f, k]
{fig=3, kiwi=4}
[1a, 1b, 2a, 2b]
[APPLE, FIG] 2
  • Verdict: stdlib. Java has no comprehension syntax, but a stream has the same parts: a source, filter and map. toList, Collectors.toCollection and Collectors.toMap choose the type of the result. flatMap does the work of two for clauses. The stream is lazy, so map runs only twice because limit(2) needs only two items.
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *words[] = {"apple", "fig", "banana", "kiwi", "cherry"};
    size_t n = sizeof words / sizeof words[0];

    // C has no comprehension. A loop fills an array and counts the items.
    size_t lengths[5];
    size_t count = 0;
    for (size_t i = 0; i < n; i++) {
        size_t len = strlen(words[i]);
        if (len > 3) {
            lengths[count++] = len;
        }
    }
    for (size_t i = 0; i < count; i++) {
        printf("%zu%s", lengths[i], i + 1 < count ? " " : "\n");
    }

    // A set of first letters: one flag for each letter.
    bool seen[26] = {false};
    for (size_t i = 0; i < n; i++) {
        seen[words[i][0] - 'a'] = true;
    }
    for (int c = 0; c < 26; c++) {
        if (seen[c]) {
            putchar('a' + c);
        }
    }
    putchar('\n');

    // Two loops nest like two for clauses.
    const char *ys = "ab";
    for (int x = 1; x <= 2; x++) {
        for (const char *y = ys; *y != '\0'; y++) {
            bool last = x == 2 && y[1] == '\0';
            printf("%d%c%s", x, *y, last ? "\n" : " ");
        }
    }
    return 0;
}
Output
5 6 4 6
abcfk
1a 1b 2a 2b
  • Verdict: idiom. C has no comprehension syntax and no growable list in the standard library. The program fills an array that is large enough and counts the items, keeps a set of letters as an array of flags, and nests two loops for the pairs.
using System;
using System.Collections.Generic;
using System.Linq;

string[] words = { "apple", "fig", "banana", "kiwi", "cherry" };

// Query syntax: from names the source, where is the filter, select is the expression.
var lengths = from w in words where w.Length > 3 select w.Length;
Console.WriteLine(string.Join(",", lengths));

// Two from clauses nest like two loops.
var pairs = from x in new[] { 1, 2 } from y in new[] { "a", "b" } select $"{x}{y}";
Console.WriteLine(string.Join(",", pairs));

// The compiler turns query syntax into method calls, so these give the same items.
var same = words.Where(w => w.Length > 3).Select(w => w.Length);
Console.WriteLine(lengths.SequenceEqual(same));

// ToHashSet and ToDictionary build other collections.
var firsts = words.Select(w => w[0]).ToHashSet();
Console.WriteLine(string.Join(",", firsts.OrderBy(c => c)));
var withI = words.Where(w => w.Contains('i')).ToDictionary(w => w, w => w.Length);
Console.WriteLine(string.Join(",", withI.Select(p => $"{p.Key}={p.Value}")));

// A query is deferred: it runs again each time a loop reads it.
var list = new List<int> { 1, 2, 3 };
var doubled = from n in list select n * 2;
list.Add(4);
Console.WriteLine(string.Join(",", doubled));
Output
5,6,4,6
1a,1b,2a,2b
True
a,b,c,f,k
fig=3,kiwi=4
2,4,6,8
  • Verdict: native. C# query syntax has from for the source, where for the filter and select for the expression, and two from clauses nest like two loops. The compiler turns the query into Where and Select calls, so the method syntax gives the same items. The last query is deferred: it reads the list when string.Join reads the query, after the program adds 4, so the result has four items.
JavaScriptGitHub
const words = ["apple", "fig", "banana", "kiwi", "cherry"];

// JavaScript has no comprehension syntax. filter and map do the same work.
console.log(words.filter((w) => w.length > 3).map((w) => w.length));

// A Set from mapped values, and an object from [key, value] pairs.
console.log([...new Set(words.map((w) => w[0]))].sort());
console.log(Object.fromEntries(words.filter((w) => w.includes("i")).map((w) => [w, w.length])));

// flatMap does the work of two for clauses.
console.log([1, 2].flatMap((x) => ["a", "b"].map((y) => `${x}${y}`)));

// Array.from with a map function builds a list from a range.
console.log(Array.from({ length: 5 }, (_, i) => i * i));

// Iterator helpers are lazy: map runs only for the items that take needs.
let calls = 0;
const firstTwo = words
  .values()
  .map((w) => {
    calls++;
    return w.toUpperCase();
  })
  .take(2)
  .toArray();
console.log(firstTwo, calls);
Output
[ 5, 6, 4, 6 ]
[ 'a', 'b', 'c', 'f', 'k' ]
{ fig: 3, kiwi: 4 }
[ '1a', '1b', '2a', '2b' ]
[ 0, 1, 4, 9, 16 ]
[ 'APPLE', 'FIG' ] 2
  • Verdict: idiom. JavaScript has no comprehension syntax. filter and map give the list, new Set gives a set, and Object.fromEntries makes an object from pairs. flatMap does the work of two for clauses. The iterator helpers on words.values() are lazy, so map runs only twice because take(2) needs only two items.
package main

import (
	"fmt"
	"maps"
	"slices"
	"strings"
)

func main() {
	words := []string{"apple", "fig", "banana", "kiwi", "cherry"}

	// Go has no comprehension. A loop with append builds the list.
	var lengths []int
	for _, w := range words {
		if len(w) > 3 {
			lengths = append(lengths, len(w))
		}
	}
	fmt.Println(lengths)

	// A map with empty struct values is a set. A loop fills a map in the same way.
	firsts := map[byte]struct{}{}
	withI := map[string]int{}
	for _, w := range words {
		firsts[w[0]] = struct{}{}
		if strings.Contains(w, "i") {
			withI[w] = len(w)
		}
	}
	fmt.Println(string(slices.Sorted(maps.Keys(firsts))), withI)

	// Two loops nest like two for clauses.
	var pairs []string
	for x := 1; x <= 2; x++ {
		for _, y := range []string{"a", "b"} {
			pairs = append(pairs, fmt.Sprint(x, y))
		}
	}
	fmt.Println(pairs)

	// An iterator function makes the items one at a time, so the loop can stop early.
	squares := func(yield func(int) bool) {
		for n := 0; ; n++ {
			if !yield(n * n) {
				return
			}
		}
	}
	var small []int
	for s := range squares {
		if s > 10 {
			break
		}
		small = append(small, s)
	}
	fmt.Println(small)
}
Output
[5 6 4 6]
abcfk map[fig:3 kiwi:4]
[1a 1b 2a 2b]
[0 1 4 9]
  • Verdict: idiom. Go has no comprehension syntax. A for loop with append builds a slice, and a loop fills a map or a set made from a map. fmt.Println prints a map with its keys in sorted order. The iterator function gives squares without end, and the range loop stops it with break.
RustGitHub
use std::collections::{BTreeMap, BTreeSet};

fn main() {
    let words = ["apple", "fig", "banana", "kiwi", "cherry"];

    // An iterator chain: a source, a filter, a map and collect.
    let lengths: Vec<usize> = words.iter().filter(|w| w.len() > 3).map(|w| w.len()).collect();
    println!("{:?}", lengths);

    // collect builds the collection that the type names.
    let firsts: BTreeSet<char> = words.iter().map(|w| w.chars().next().unwrap()).collect();
    let with_i: BTreeMap<&str, usize> =
        words.iter().filter(|w| w.contains('i')).map(|w| (*w, w.len())).collect();
    println!("{:?} {:?}", firsts, with_i);

    // flat_map does the work of two for clauses.
    let pairs: Vec<String> = (1..=2)
        .flat_map(|x| ["a", "b"].iter().map(move |y| format!("{x}{y}")))
        .collect();
    println!("{:?}", pairs);

    // Adapters are lazy: nothing runs until collect, and take stops the work early.
    let mut calls = 0;
    let first_two: Vec<String> = words
        .iter()
        .map(|w| {
            calls += 1;
            w.to_uppercase()
        })
        .take(2)
        .collect();
    println!("{:?} {}", first_two, calls);
}
Output
[5, 6, 4, 6]
{'a', 'b', 'c', 'f', 'k'} {"fig": 3, "kiwi": 4}
["1a", "1b", "2a", "2b"]
["APPLE", "FIG"] 2
  • Verdict: stdlib. Rust has no comprehension syntax, but an iterator chain has the same parts. collect builds the type that the program names, here a Vec, a BTreeSet and a BTreeMap. flat_map does the work of two for clauses. The adapters are lazy, so the closure in map runs only twice because take(2) needs only two items.
  • Eager and lazy. A list comprehension builds the whole result at once. A generator expression, a Java stream, a Rust iterator chain, a C++ view and a C# query make the items when the program reads them. The Java documentation says that intermediate operations "are always lazy; executing an intermediate operation such as filter() does not actually perform any filtering"13. Rust says: "Iterators (and iterator adapters) are lazy. This means that just creating an iterator doesn’t do a whole lot. Nothing really happens until you call next"14. C++ says that range adaptors "are applied to views lazily. Adaptors can be composed into pipelines, so that their actions take place as the view is iterated"15.
  • Deferred queries. A lazy query runs again each time the program reads it, so it sees changes to its source. C# says: "A query is distinct from the results that it produces"16, and a query variable "is always an enumerable type that produces a sequence of elements when iterated over"16. The C# example adds an item to the list after it makes the query, and the query result contains the new item.
  • Flat map. Two generators in one comprehension do the same work as a flat map. MDN says that flatMap "is identical to a map() followed by a flat() of depth 1"17. See compute the Cartesian product.
  • Collection pipelines. A long chain of filter, map, sort and reduce calls is a collection pipeline. A comprehension covers only the map and the filter, so a pipeline is the more general form. See replace loop with pipeline and reduce a list to a value.
  • Iterator functions. Go has no comprehension, but a range loop accepts a function that calls yield for each value, so a function can produce values one at a time18. Python generators and JavaScript generator functions do the same with yield. See iterators.

Pitfalls

  • Too much in one expression. A comprehension with three for clauses, two filters and a conditional expression is hard to read. Use a loop or a named function when the comprehension does not fit on one or two lines.
  • The filter and the conditional expression. In Python, [x for x in s if c] drops the items that fail c, but [x if c else y for x in s] keeps every item and changes some of them. The if after the for is a filter, and the if before the for is part of the expression.
  • The order of the clauses. The first for clause is the outer loop. To flatten a list of rows, write [x for row in m for x in row]. The other order uses row before it has a value.
  • Side effects. A comprehension that runs only for its side effects, such as [print(x) for x in s], builds a list that the program does not use. Rust gives a warning for a lazy chain that is never used, because "iterators are lazy and do nothing unless consumed"14. Use a loop.
  • A lazy result used twice. A generator expression or a Java stream can be read only once. The second read of a Python generator gives no items. The Java documentation says: "The elements of a stream are only visited once during the life of a stream. Like an Iterator, a new stream must be generated to revisit the same elements of the source"13. Make a list when the program needs the items more than once.
  • A deferred query and a changing source. A lazy query reads its source when the program reads the query, not when the program makes it. If the source changes between the two, the result changes too. Make a list at once when the program needs a snapshot.
  • The first source runs at once. A Python generator expression evaluates its leftmost source when the program makes it, and evaluates the rest later. An error in the first source appears at once, and an error in the other parts appears when the program reads the items.

Cost

A comprehension does the same work as the loop that it replaces: the expression runs once for each item that passes the filter, and the filter runs once for each item of the source. A list, set or dict comprehension uses memory for the whole result. A generator expression uses memory for one item at a time. PEP 289 gives an example: "Memory is conserved by using a generator expression instead: sum(x*x for x in range(10))"8.

CPython first compiled each comprehension as a nested function. PEP 709 says: "Comprehensions are currently compiled as nested functions, which provides isolation of the comprehension’s iteration variable, but is inefficient at runtime. This PEP proposes to inline list, dictionary, and set comprehensions into the code where they are defined"19. Kotlin map on a list "applies the given lambda function to each subsequent element and returns the list of the lambda results"20, so a chain of eager calls makes a new list at each step. A lazy chain of adapters, such as a Rust iterator chain, makes no lists between the steps.

History

Set-builder notation came first, in set theory. Wikipedia notes that "Specifying sets by member properties is allowed by the axiom schema of specification. This is also known as set comprehension and set abstraction"2.

Wikipedia gives this history for programming languages21. "The SETL programming language (1969) has a set formation construct which is similar to list comprehensions." Rod Burstall and John Darlington used the word comprehension for this construct in their description of the functional language NPL in 1977, and David Turner recalls that "it was Phil Wadler who coined the better term list comprehension". Turner's lazy functional language Miranda had list comprehensions, and "The subsequently developed standard pure lazy functional language Haskell includes many of Miranda's features, including list comprehensions." Wikipedia also says that "Comprehensions were proposed as a query notation for databases".

Python added list comprehensions with PEP 2024, dict comprehensions with PEP 2747 and generator expressions with PEP 2898. C# added query expressions with LINQ. They use the keywords from, where and select16. Languages that do not have comprehension syntax, such as Java, Rust, JavaScript and Kotlin, added lazy or eager chains of filter and map to their standard libraries13142220.

References

  1. Data Structures, The Python Tutorial, 5.1.3 List Comprehensions
  2. Set-builder notation, Wikipedia, Introduction
  3. Expressions, The Python Language Reference, 6.2.4 Displays for lists, sets and dictionaries; 6.2.7 Generator expressions
  4. PEP 202, List Comprehensions, Rationale
  5. Expressions, Haskell 2010 Language Report, 3.11 List Comprehensions
  6. List Comprehensions, Erlang System Documentation, Simple Examples
  7. PEP 274, Dict Comprehensions, Abstract
  8. PEP 289, Generator Expressions, Abstract; Rationale
  9. PEP 572, Assignment Expressions, Scope of the target
  10. Write C# LINQ queries to query data, Microsoft Learn, Introduction
  11. For Comprehensions, Tour of Scala, Introduction
  12. Comprehensions, Elixir documentation, Introduction; Generators and filters
  13. Package java.util.stream, Java SE 25 API, Stream operations and pipelines
  14. Module iter, The Rust Standard Library, Laziness
  15. Ranges library, cppreference.com, Introduction
  16. Query expression basics, Microsoft Learn, What is a query expression?; Query variable
  17. Array.prototype.flatMap(), MDN Web Docs, Description
  18. The Go Programming Language Specification, For statements with range clause
  19. PEP 709, Inlined comprehensions, Abstract
  20. Transform collections, Kotlin documentation, Map
  21. List comprehension, Wikipedia, History
  22. Iterator, MDN Web Docs, Iterator helper methods

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/NYN64N/text.yaml