ArticleslgStudy

science

List comprehension

List comprehension is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand List comprehension rather than just read about it. In short: A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.

Key takeaways

  • List comprehension belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect List comprehension to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of List comprehension from memory before moving on to harder problems.

Reference excerpt

A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.

Overview Consider the following example in mathematical set-builder notation.

S={2⋅x∣x∈ℕ, x2>3} or often

S={2⋅x:x∈ℕ, x2>3} This can be read, "S is the set of all numbers "2 times x" SUCH THAT x is an ELEMENT or MEMBER of the set of natural numbers (ℕ), AND x squared is greater than 3." The smallest natural number, x = 1, fails to satisfy the condition x2>3 (the condition 12>3 is false) so 2 ·1 is not included in S. The next natural number, 2, does satisfy the condition (22>3) as does every other natural number. Thus x consists of 2, 3, 4, 5... Since the set S consists of all numbers "2 times x" it is given by S = {4, 6, 8, 10,...}. S is, in other words, the set of all even numbers greater than 2. In this annotated version of the example:

S={2⋅x⏟output expression∣x⏟variable∈ℕ⏟input set, x2>3⏟predicate} x is the variable representing members of an input set. ℕ represents the input set, which in this example is the set of natural numbers x2>3 is a predicate expression acting as a filter on members of the input set. 2⋅x is an output expression producing members of the new set from members of the input set that satisfy the predicate expression. {} braces indicate that the result is a set ∣ , the vertical bar is read as "SUCH THAT". The bar and the colon ":" are used interchangeably. commas separate the predicates and can be read as "AND". A list comprehension has the same syntactic components to represent generation of a list in order from an input list or iterator:

A variable representing members of an input list. An input list (or iterator). An optional predicate expression. And an output expression producing members of the output list from members of the input iterable that satisfy the predicate. The order of generation of members of the output list is based on the order of items in the input. In Haskell's list comprehension syntax, this set-builder construct would be written similarly, as:

Here, the list [0..] represents ℕ, x^2>3 represents the predicate, and 2*x represents the output expression. List comprehensions give results in a defined order (unlike the members of sets); and list comprehensions may generate the members of a list in order, rather than produce the entirety of the list thus allowing, for example, the previous Haskell definition of the members of an infinite list.

History The existence of related constructs predates the use of the term "List Comprehension". The SETL programming language (1969) has a set formation construct which is similar to list comprehensions. E.g., this code prints all prime numbers from 2 to N:

print([n in [2..N] | ∀ m in {2..n - 1} | n mod m > 0]);

The computer algebra system Axiom (1973) has a similar construct that processes streams. The first use of the term "comprehension" for such constructs was in Rod Burstall and John Darlington's description of their functional programming language NPL from 1977. In his retrospective "Some History of Functional Programming Languages", David Turner recalls:

NPL was implemented in POP2 by Burstall and used for Darlington’s work on program transformation (Burstall & Darlington 1977). The language was first order, strongly (but not polymorphically) typed, purely functional, call-by-value. It also had "set expressions" e.g., setofeven (X) <= <:x : x in X & even(x):>}} In a footnote attached to the term "list comprehension", Turner also notes:

I initially called these ZF expressions, a reference to Zermelo–Fraenkel set theory – it was Phil Wadler who coined the better term list comprehension. Burstall and Darlington's work with NPL influenced many functional programming languages during the 1980s, but not all included list comprehensions. An exception was Turner's influential, pure, lazy, functional programming language Miranda, released in 1985. The subsequently developed standard pure lazy functional language Haskell includes many of Miranda's features, including list comprehensions. Comprehensions were proposed as a query notation for databases and were implemented in the Kleisli database query language.

Examples in different programming languages

Similar constructs

Monad comprehension In Haskell, a monad comprehension is a generalization of the list comprehension to other monads in functional programming.

Set comprehension The Python language introduces syntax for set comprehensions starting in version 2.7. Similar in form to list comprehensions, set comprehensions generate Python sets instead of lists.

Racket set comprehensions generate Racket sets instead of lists.

Dictionary comprehension The Python language introduced a new syntax for dictionary comprehensions in version 2.7, similar in form to list comprehensions but which generate Python dicts instead of lists.

Racket hash table comprehensions generate Racket hash tables (one implementation of the Racket dictionary type).

Parallel list comprehension The Glasgow Haskell Compiler has an extension named parallel list comprehension (also called zip-comprehension) that permits multiple independent branches of qualifiers within the list comprehension syntax. Whereas qualifiers separated by commas are dependent ("nested"), qualifier branches separated by pipes are evaluated in parallel (this refers to no form of multithreadedness: it merely means that the branches are zipped).

Racket's comprehensions standard library contains parallel and nested versions of its comprehensions, distinguished by "for" vs "for*" in the name. For example, the vector comprehensions "for/vector" and "for*/vector" create vectors by parallel versus nested iteration over sequences. The following is Racket code for the Haskell list comprehension examples.

In Python, we could do as follows:

In Julia, practically the same results can be achieved as follows:

with the only difference that instead of lists, in Julia, we have arrays.

XQuery and XPath Like the original NPL use, these are fundamentally database access languages. This makes the comprehension concept more important, because it is computationally infeasible to retrieve the entire list and operate on it (the initial 'entire list' may be an entire Extensible Markup Language (XML) database). In XPath, the expression:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with List comprehension

Start with the simplest possible case. Write down what List comprehension claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to List comprehension before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about List comprehension ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of List comprehension

In research
List comprehension appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses List comprehension in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
List comprehension is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming constructs, Programming language comparisons, so understanding it makes those chapters shorter.
In everyday life
Look for List comprehension outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “List comprehension” →

How to study List comprehension in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what List comprehension means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain List comprehension out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is List comprehension in simple terms?

A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical set-builder notation (set comprehension) as distinct from the use of map and filter functions.

Why does List comprehension matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study List comprehension?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on List comprehension.

Tags

  • Programming constructs
  • Programming language comparisons

Keep exploring